Dan Brown

Merge branch 'master' into release ready for v0.14

Showing 199 changed files with 2061 additions and 1033 deletions
### For Feature Requests
Desired Feature:
### For Bug Reports
PHP Version:
MySQL Version:
* BookStack Version:
* PHP Version:
* MySQL Version:
Expected Behavior:
##### Expected Behavior
Actual Behavior:
##### Actual Behavior
......
......@@ -13,3 +13,4 @@ _ide_helper.php
/storage/debugbar
.phpstorm.meta.php
yarn.lock
/bin
\ No newline at end of file
......
......@@ -17,9 +17,7 @@ addons:
before_script:
- mysql -u root -e 'create database `bookstack-test`;'
- composer config -g github-oauth.github.com $GITHUB_ACCESS_TOKEN
- phpenv config-rm xdebug.ini
- composer self-update
- composer dump-autoload --no-interaction
- composer install --prefer-dist --no-interaction
- php artisan clear-compiled -n
......
......@@ -5,6 +5,8 @@ class Chapter extends Entity
{
protected $fillable = ['name', 'description', 'priority', 'book_id'];
protected $with = ['book'];
/**
* Get the book this chapter is within.
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
......@@ -16,11 +18,12 @@ class Chapter extends Entity
/**
* Get the pages that this chapter contains.
* @param string $dir
* @return mixed
*/
public function pages()
public function pages($dir = 'ASC')
{
return $this->hasMany(Page::class)->orderBy('priority', 'ASC');
return $this->hasMany(Page::class)->orderBy('priority', $dir);
}
/**
......
......@@ -4,6 +4,8 @@
class Entity extends Ownable
{
protected $fieldsToSearch = ['name', 'description'];
/**
* Compares this entity to another given entity.
* Matches by comparing class and id.
......@@ -157,7 +159,7 @@ class Entity extends Ownable
* @param string[] array $wheres
* @return mixed
*/
public function fullTextSearchQuery($fieldsToSearch, $terms, $wheres = [])
public function fullTextSearchQuery($terms, $wheres = [])
{
$exactTerms = [];
$fuzzyTerms = [];
......@@ -181,16 +183,16 @@ class Entity extends Ownable
// Perform fulltext search if relevant terms exist.
if ($isFuzzy) {
$termString = implode(' ', $fuzzyTerms);
$fields = implode(',', $fieldsToSearch);
$fields = implode(',', $this->fieldsToSearch);
$search = $search->selectRaw('*, MATCH(name) AGAINST(? IN BOOLEAN MODE) AS title_relevance', [$termString]);
$search = $search->whereRaw('MATCH(' . $fields . ') AGAINST(? IN BOOLEAN MODE)', [$termString]);
}
// Ensure at least one exact term matches if in search
if (count($exactTerms) > 0) {
$search = $search->where(function ($query) use ($exactTerms, $fieldsToSearch) {
$search = $search->where(function ($query) use ($exactTerms) {
foreach ($exactTerms as $exactTerm) {
foreach ($fieldsToSearch as $field) {
foreach ($this->fieldsToSearch as $field) {
$query->orWhere($field, 'like', $exactTerm);
}
}
......
......@@ -2,7 +2,7 @@
use BookStack\Exceptions\FileUploadException;
use BookStack\Attachment;
use BookStack\Repos\PageRepo;
use BookStack\Repos\EntityRepo;
use BookStack\Services\AttachmentService;
use Illuminate\Http\Request;
......@@ -10,19 +10,19 @@ class AttachmentController extends Controller
{
protected $attachmentService;
protected $attachment;
protected $pageRepo;
protected $entityRepo;
/**
* AttachmentController constructor.
* @param AttachmentService $attachmentService
* @param Attachment $attachment
* @param PageRepo $pageRepo
* @param EntityRepo $entityRepo
*/
public function __construct(AttachmentService $attachmentService, Attachment $attachment, PageRepo $pageRepo)
public function __construct(AttachmentService $attachmentService, Attachment $attachment, EntityRepo $entityRepo)
{
$this->attachmentService = $attachmentService;
$this->attachment = $attachment;
$this->pageRepo = $pageRepo;
$this->entityRepo = $entityRepo;
parent::__construct();
}
......@@ -40,7 +40,7 @@ class AttachmentController extends Controller
]);
$pageId = $request->get('uploaded_to');
$page = $this->pageRepo->getById($pageId, true);
$page = $this->entityRepo->getById('page', $pageId, true);
$this->checkPermission('attachment-create-all');
$this->checkOwnablePermission('page-update', $page);
......@@ -70,14 +70,14 @@ class AttachmentController extends Controller
]);
$pageId = $request->get('uploaded_to');
$page = $this->pageRepo->getById($pageId, true);
$page = $this->entityRepo->getById('page', $pageId, true);
$attachment = $this->attachment->findOrFail($attachmentId);
$this->checkOwnablePermission('page-update', $page);
$this->checkOwnablePermission('attachment-create', $attachment);
if (intval($pageId) !== intval($attachment->uploaded_to)) {
return $this->jsonError('Page mismatch during attached file update');
return $this->jsonError(trans('errors.attachment_page_mismatch'));
}
$uploadedFile = $request->file('file');
......@@ -106,18 +106,18 @@ class AttachmentController extends Controller
]);
$pageId = $request->get('uploaded_to');
$page = $this->pageRepo->getById($pageId, true);
$page = $this->entityRepo->getById('page', $pageId, true);
$attachment = $this->attachment->findOrFail($attachmentId);
$this->checkOwnablePermission('page-update', $page);
$this->checkOwnablePermission('attachment-create', $attachment);
if (intval($pageId) !== intval($attachment->uploaded_to)) {
return $this->jsonError('Page mismatch during attachment update');
return $this->jsonError(trans('errors.attachment_page_mismatch'));
}
$attachment = $this->attachmentService->updateFile($attachment, $request->all());
return $attachment;
return response()->json($attachment);
}
/**
......@@ -134,7 +134,7 @@ class AttachmentController extends Controller
]);
$pageId = $request->get('uploaded_to');
$page = $this->pageRepo->getById($pageId, true);
$page = $this->entityRepo->getById('page', $pageId, true);
$this->checkPermission('attachment-create-all');
$this->checkOwnablePermission('page-update', $page);
......@@ -153,7 +153,7 @@ class AttachmentController extends Controller
*/
public function listForPage($pageId)
{
$page = $this->pageRepo->getById($pageId, true);
$page = $this->entityRepo->getById('page', $pageId, true);
$this->checkOwnablePermission('page-view', $page);
return response()->json($page->attachments);
}
......@@ -170,12 +170,12 @@ class AttachmentController extends Controller
'files' => 'required|array',
'files.*.id' => 'required|integer',
]);
$page = $this->pageRepo->getById($pageId);
$page = $this->entityRepo->getById('page', $pageId);
$this->checkOwnablePermission('page-update', $page);
$attachments = $request->get('files');
$this->attachmentService->updateFileOrderWithinPage($attachments, $pageId);
return response()->json(['message' => 'Attachment order updated']);
return response()->json(['message' => trans('entities.attachments_order_updated')]);
}
/**
......@@ -186,7 +186,7 @@ class AttachmentController extends Controller
public function get($attachmentId)
{
$attachment = $this->attachment->findOrFail($attachmentId);
$page = $this->pageRepo->getById($attachment->uploaded_to);
$page = $this->entityRepo->getById('page', $attachment->uploaded_to);
$this->checkOwnablePermission('page-view', $page);
if ($attachment->external) {
......@@ -210,6 +210,6 @@ class AttachmentController extends Controller
$attachment = $this->attachment->findOrFail($attachmentId);
$this->checkOwnablePermission('attachment-delete', $attachment);
$this->attachmentService->deleteFile($attachment);
return response()->json(['message' => 'Attachment deleted']);
return response()->json(['message' => trans('entities.attachments_deleted')]);
}
}
......
......@@ -52,7 +52,7 @@ class ForgotPasswordController extends Controller
);
if ($response === Password::RESET_LINK_SENT) {
$message = 'A password reset link has been sent to ' . $request->get('email') . '.';
$message = trans('auth.reset_password_sent_success', ['email' => $request->get('email')]);
session()->flash('success', $message);
return back()->with('status', trans($response));
}
......
......@@ -87,7 +87,7 @@ class LoginController extends Controller
// Check for users with same email already
$alreadyUser = $user->newQuery()->where('email', '=', $user->email)->count() > 0;
if ($alreadyUser) {
throw new AuthException('A user with the email ' . $user->email . ' already exists but with different credentials.');
throw new AuthException(trans('errors.error_user_exists_different_creds', ['email' => $user->email]));
}
$user->save();
......
......@@ -3,6 +3,7 @@
namespace BookStack\Http\Controllers\Auth;
use BookStack\Exceptions\ConfirmationEmailException;
use BookStack\Exceptions\SocialSignInException;
use BookStack\Exceptions\UserRegistrationException;
use BookStack\Repos\UserRepo;
use BookStack\Services\EmailConfirmationService;
......@@ -82,7 +83,7 @@ class RegisterController extends Controller
protected function checkRegistrationAllowed()
{
if (!setting('registration-enabled')) {
throw new UserRegistrationException('Registrations are currently disabled.', '/login');
throw new UserRegistrationException(trans('auth.registrations_disabled'), '/login');
}
}
......@@ -147,7 +148,7 @@ class RegisterController extends Controller
$restrictedEmailDomains = explode(',', str_replace(' ', '', setting('registration-restrict')));
$userEmailDomain = $domain = substr(strrchr($userData['email'], "@"), 1);
if (!in_array($userEmailDomain, $restrictedEmailDomains)) {
throw new UserRegistrationException('That email domain does not have access to this application', '/register');
throw new UserRegistrationException(trans('auth.registration_email_domain_invalid'), '/register');
}
}
......@@ -169,7 +170,7 @@ class RegisterController extends Controller
}
auth()->login($newUser);
session()->flash('success', 'Thanks for signing up! You are now registered and signed in.');
session()->flash('success', trans('auth.register_success'));
return redirect($this->redirectPath());
}
......@@ -262,7 +263,7 @@ class RegisterController extends Controller
return $this->socialRegisterCallback($socialDriver);
}
} else {
throw new SocialSignInException('No action defined', '/login');
throw new SocialSignInException(trans('errors.social_no_action_defined'), '/login');
}
return redirect()->back();
}
......
......@@ -41,7 +41,7 @@ class ResetPasswordController extends Controller
*/
protected function sendResetResponse($response)
{
$message = 'Your password has been successfully reset.';
$message = trans('auth.reset_password_success');
session()->flash('success', $message);
return redirect($this->redirectPath())
->with('status', trans($response));
......
<?php namespace BookStack\Http\Controllers;
use Activity;
use BookStack\Repos\EntityRepo;
use BookStack\Repos\UserRepo;
use Illuminate\Http\Request;
use BookStack\Http\Requests;
use BookStack\Repos\BookRepo;
use BookStack\Repos\ChapterRepo;
use BookStack\Repos\PageRepo;
use Illuminate\Http\Response;
use Views;
class BookController extends Controller
{
protected $bookRepo;
protected $pageRepo;
protected $chapterRepo;
protected $entityRepo;
protected $userRepo;
/**
* BookController constructor.
* @param BookRepo $bookRepo
* @param PageRepo $pageRepo
* @param ChapterRepo $chapterRepo
* @param EntityRepo $entityRepo
* @param UserRepo $userRepo
*/
public function __construct(BookRepo $bookRepo, PageRepo $pageRepo, ChapterRepo $chapterRepo, UserRepo $userRepo)
public function __construct(EntityRepo $entityRepo, UserRepo $userRepo)
{
$this->bookRepo = $bookRepo;
$this->pageRepo = $pageRepo;
$this->chapterRepo = $chapterRepo;
$this->entityRepo = $entityRepo;
$this->userRepo = $userRepo;
parent::__construct();
}
......@@ -39,9 +31,9 @@ class BookController extends Controller
*/
public function index()
{
$books = $this->bookRepo->getAllPaginated(10);
$recents = $this->signedIn ? $this->bookRepo->getRecentlyViewed(4, 0) : false;
$popular = $this->bookRepo->getPopular(4, 0);
$books = $this->entityRepo->getAllPaginated('book', 10);
$recents = $this->signedIn ? $this->entityRepo->getRecentlyViewed('book', 4, 0) : false;
$popular = $this->entityRepo->getPopular('book', 4, 0);
$this->setPageTitle('Books');
return view('books/index', ['books' => $books, 'recents' => $recents, 'popular' => $popular]);
}
......@@ -53,7 +45,7 @@ class BookController extends Controller
public function create()
{
$this->checkPermission('book-create-all');
$this->setPageTitle('Create New Book');
$this->setPageTitle(trans('entities.books_create'));
return view('books/create');
}
......@@ -70,7 +62,7 @@ class BookController extends Controller
'name' => 'required|string|max:255',
'description' => 'string|max:1000'
]);
$book = $this->bookRepo->createFromInput($request->all());
$book = $this->entityRepo->createFromInput('book', $request->all());
Activity::add($book, 'book_create', $book->id);
return redirect($book->getUrl());
}
......@@ -82,9 +74,9 @@ class BookController extends Controller
*/
public function show($slug)
{
$book = $this->bookRepo->getBySlug($slug);
$book = $this->entityRepo->getBySlug('book', $slug);
$this->checkOwnablePermission('book-view', $book);
$bookChildren = $this->bookRepo->getChildren($book);
$bookChildren = $this->entityRepo->getBookChildren($book);
Views::add($book);
$this->setPageTitle($book->getShortName());
return view('books/show', ['book' => $book, 'current' => $book, 'bookChildren' => $bookChildren]);
......@@ -97,9 +89,9 @@ class BookController extends Controller
*/
public function edit($slug)
{
$book = $this->bookRepo->getBySlug($slug);
$book = $this->entityRepo->getBySlug('book', $slug);
$this->checkOwnablePermission('book-update', $book);
$this->setPageTitle('Edit Book ' . $book->getShortName());
$this->setPageTitle(trans('entities.books_edit_named',['bookName'=>$book->getShortName()]));
return view('books/edit', ['book' => $book, 'current' => $book]);
}
......@@ -111,13 +103,13 @@ class BookController extends Controller
*/
public function update(Request $request, $slug)
{
$book = $this->bookRepo->getBySlug($slug);
$book = $this->entityRepo->getBySlug('book', $slug);
$this->checkOwnablePermission('book-update', $book);
$this->validate($request, [
'name' => 'required|string|max:255',
'description' => 'string|max:1000'
]);
$book = $this->bookRepo->updateFromInput($book, $request->all());
$book = $this->entityRepo->updateFromInput('book', $book, $request->all());
Activity::add($book, 'book_update', $book->id);
return redirect($book->getUrl());
}
......@@ -129,9 +121,9 @@ class BookController extends Controller
*/
public function showDelete($bookSlug)
{
$book = $this->bookRepo->getBySlug($bookSlug);
$book = $this->entityRepo->getBySlug('book', $bookSlug);
$this->checkOwnablePermission('book-delete', $book);
$this->setPageTitle('Delete Book ' . $book->getShortName());
$this->setPageTitle(trans('entities.books_delete_named', ['bookName'=>$book->getShortName()]));
return view('books/delete', ['book' => $book, 'current' => $book]);
}
......@@ -142,11 +134,11 @@ class BookController extends Controller
*/
public function sort($bookSlug)
{
$book = $this->bookRepo->getBySlug($bookSlug);
$book = $this->entityRepo->getBySlug('book', $bookSlug);
$this->checkOwnablePermission('book-update', $book);
$bookChildren = $this->bookRepo->getChildren($book, true);
$books = $this->bookRepo->getAll(false);
$this->setPageTitle('Sort Book ' . $book->getShortName());
$bookChildren = $this->entityRepo->getBookChildren($book, true);
$books = $this->entityRepo->getAll('book', false);
$this->setPageTitle(trans('entities.books_sort_named', ['bookName'=>$book->getShortName()]));
return view('books/sort', ['book' => $book, 'current' => $book, 'books' => $books, 'bookChildren' => $bookChildren]);
}
......@@ -158,8 +150,8 @@ class BookController extends Controller
*/
public function getSortItem($bookSlug)
{
$book = $this->bookRepo->getBySlug($bookSlug);
$bookChildren = $this->bookRepo->getChildren($book);
$book = $this->entityRepo->getBySlug('book', $bookSlug);
$bookChildren = $this->entityRepo->getBookChildren($book);
return view('books/sort-box', ['book' => $book, 'bookChildren' => $bookChildren]);
}
......@@ -171,7 +163,7 @@ class BookController extends Controller
*/
public function saveSort($bookSlug, Request $request)
{
$book = $this->bookRepo->getBySlug($bookSlug);
$book = $this->entityRepo->getBySlug('book', $bookSlug);
$this->checkOwnablePermission('book-update', $book);
// Return if no map sent
......@@ -190,13 +182,13 @@ class BookController extends Controller
$priority = $bookChild->sort;
$id = intval($bookChild->id);
$isPage = $bookChild->type == 'page';
$bookId = $this->bookRepo->exists($bookChild->book) ? intval($bookChild->book) : $defaultBookId;
$bookId = $this->entityRepo->exists('book', $bookChild->book) ? intval($bookChild->book) : $defaultBookId;
$chapterId = ($isPage && $bookChild->parentChapter === false) ? 0 : intval($bookChild->parentChapter);
$model = $isPage ? $this->pageRepo->getById($id) : $this->chapterRepo->getById($id);
$model = $this->entityRepo->getById($isPage?'page':'chapter', $id);
// Update models only if there's a change in parent chain or ordering.
if ($model->priority !== $priority || $model->book_id !== $bookId || ($isPage && $model->chapter_id !== $chapterId)) {
$isPage ? $this->pageRepo->changeBook($bookId, $model) : $this->chapterRepo->changeBook($bookId, $model);
$this->entityRepo->changeBook($isPage?'page':'chapter', $bookId, $model);
$model->priority = $priority;
if ($isPage) $model->chapter_id = $chapterId;
$model->save();
......@@ -211,12 +203,12 @@ class BookController extends Controller
// Add activity for books
foreach ($sortedBooks as $bookId) {
$updatedBook = $this->bookRepo->getById($bookId);
$updatedBook = $this->entityRepo->getById('book', $bookId);
Activity::add($updatedBook, 'book_sort', $updatedBook->id);
}
// Update permissions on changed models
$this->bookRepo->buildJointPermissions($updatedModels);
$this->entityRepo->buildJointPermissions($updatedModels);
return redirect($book->getUrl());
}
......@@ -228,11 +220,10 @@ class BookController extends Controller
*/
public function destroy($bookSlug)
{
$book = $this->bookRepo->getBySlug($bookSlug);
$book = $this->entityRepo->getBySlug('book', $bookSlug);
$this->checkOwnablePermission('book-delete', $book);
Activity::addMessage('book_delete', 0, $book->name);
Activity::removeEntity($book);
$this->bookRepo->destroy($book);
$this->entityRepo->destroyBook($book);
return redirect('/books');
}
......@@ -243,7 +234,7 @@ class BookController extends Controller
*/
public function showRestrict($bookSlug)
{
$book = $this->bookRepo->getBySlug($bookSlug);
$book = $this->entityRepo->getBySlug('book', $bookSlug);
$this->checkOwnablePermission('restrictions-manage', $book);
$roles = $this->userRepo->getRestrictableRoles();
return view('books/restrictions', [
......@@ -261,10 +252,10 @@ class BookController extends Controller
*/
public function restrict($bookSlug, Request $request)
{
$book = $this->bookRepo->getBySlug($bookSlug);
$book = $this->entityRepo->getBySlug('book', $bookSlug);
$this->checkOwnablePermission('restrictions-manage', $book);
$this->bookRepo->updateEntityPermissionsFromRequest($request, $book);
session()->flash('success', 'Book Restrictions Updated');
$this->entityRepo->updateEntityPermissionsFromRequest($request, $book);
session()->flash('success', trans('entities.books_permissions_updated'));
return redirect($book->getUrl());
}
}
......
<?php namespace BookStack\Http\Controllers;
use Activity;
use BookStack\Repos\EntityRepo;
use BookStack\Repos\UserRepo;
use Illuminate\Http\Request;
use BookStack\Http\Requests;
use BookStack\Repos\BookRepo;
use BookStack\Repos\ChapterRepo;
use Illuminate\Http\Response;
use Views;
class ChapterController extends Controller
{
protected $bookRepo;
protected $chapterRepo;
protected $userRepo;
protected $entityRepo;
/**
* ChapterController constructor.
* @param BookRepo $bookRepo
* @param ChapterRepo $chapterRepo
* @param EntityRepo $entityRepo
* @param UserRepo $userRepo
*/
public function __construct(BookRepo $bookRepo, ChapterRepo $chapterRepo, UserRepo $userRepo)
public function __construct(EntityRepo $entityRepo, UserRepo $userRepo)
{
$this->bookRepo = $bookRepo;
$this->chapterRepo = $chapterRepo;
$this->entityRepo = $entityRepo;
$this->userRepo = $userRepo;
parent::__construct();
}
......@@ -36,9 +32,9 @@ class ChapterController extends Controller
*/
public function create($bookSlug)
{
$book = $this->bookRepo->getBySlug($bookSlug);
$book = $this->entityRepo->getBySlug('book', $bookSlug);
$this->checkOwnablePermission('chapter-create', $book);
$this->setPageTitle('Create New Chapter');
$this->setPageTitle(trans('entities.chapters_create'));
return view('chapters/create', ['book' => $book, 'current' => $book]);
}
......@@ -54,12 +50,12 @@ class ChapterController extends Controller
'name' => 'required|string|max:255'
]);
$book = $this->bookRepo->getBySlug($bookSlug);
$book = $this->entityRepo->getBySlug('book', $bookSlug);
$this->checkOwnablePermission('chapter-create', $book);
$input = $request->all();
$input['priority'] = $this->bookRepo->getNewPriority($book);
$chapter = $this->chapterRepo->createFromInput($input, $book);
$input['priority'] = $this->entityRepo->getNewBookPriority($book);
$chapter = $this->entityRepo->createFromInput('chapter', $input, $book);
Activity::add($chapter, 'chapter_create', $book->id);
return redirect($chapter->getUrl());
}
......@@ -72,15 +68,14 @@ class ChapterController extends Controller
*/
public function show($bookSlug, $chapterSlug)
{
$book = $this->bookRepo->getBySlug($bookSlug);
$chapter = $this->chapterRepo->getBySlug($chapterSlug, $book->id);
$chapter = $this->entityRepo->getBySlug('chapter', $chapterSlug, $bookSlug);
$this->checkOwnablePermission('chapter-view', $chapter);
$sidebarTree = $this->bookRepo->getChildren($book);
$sidebarTree = $this->entityRepo->getBookChildren($chapter->book);
Views::add($chapter);
$this->setPageTitle($chapter->getShortName());
$pages = $this->chapterRepo->getChildren($chapter);
$pages = $this->entityRepo->getChapterChildren($chapter);
return view('chapters/show', [
'book' => $book,
'book' => $chapter->book,
'chapter' => $chapter,
'current' => $chapter,
'sidebarTree' => $sidebarTree,
......@@ -96,11 +91,10 @@ class ChapterController extends Controller
*/
public function edit($bookSlug, $chapterSlug)
{
$book = $this->bookRepo->getBySlug($bookSlug);
$chapter = $this->chapterRepo->getBySlug($chapterSlug, $book->id);
$chapter = $this->entityRepo->getBySlug('chapter', $chapterSlug, $bookSlug);
$this->checkOwnablePermission('chapter-update', $chapter);
$this->setPageTitle('Edit Chapter' . $chapter->getShortName());
return view('chapters/edit', ['book' => $book, 'chapter' => $chapter, 'current' => $chapter]);
$this->setPageTitle(trans('entities.chapters_edit_named', ['chapterName' => $chapter->getShortName()]));
return view('chapters/edit', ['book' => $chapter->book, 'chapter' => $chapter, 'current' => $chapter]);
}
/**
......@@ -112,16 +106,15 @@ class ChapterController extends Controller
*/
public function update(Request $request, $bookSlug, $chapterSlug)
{
$book = $this->bookRepo->getBySlug($bookSlug);
$chapter = $this->chapterRepo->getBySlug($chapterSlug, $book->id);
$chapter = $this->entityRepo->getBySlug('chapter', $chapterSlug, $bookSlug);
$this->checkOwnablePermission('chapter-update', $chapter);
if ($chapter->name !== $request->get('name')) {
$chapter->slug = $this->chapterRepo->findSuitableSlug($request->get('name'), $book->id, $chapter->id);
$chapter->slug = $this->entityRepo->findSuitableSlug('chapter', $request->get('name'), $chapter->id, $chapter->book->id);
}
$chapter->fill($request->all());
$chapter->updated_by = user()->id;
$chapter->save();
Activity::add($chapter, 'chapter_update', $book->id);
Activity::add($chapter, 'chapter_update', $chapter->book->id);
return redirect($chapter->getUrl());
}
......@@ -133,11 +126,10 @@ class ChapterController extends Controller
*/
public function showDelete($bookSlug, $chapterSlug)
{
$book = $this->bookRepo->getBySlug($bookSlug);
$chapter = $this->chapterRepo->getBySlug($chapterSlug, $book->id);
$chapter = $this->entityRepo->getBySlug('chapter', $chapterSlug, $bookSlug);
$this->checkOwnablePermission('chapter-delete', $chapter);
$this->setPageTitle('Delete Chapter' . $chapter->getShortName());
return view('chapters/delete', ['book' => $book, 'chapter' => $chapter, 'current' => $chapter]);
$this->setPageTitle(trans('entities.chapters_delete_named', ['chapterName' => $chapter->getShortName()]));
return view('chapters/delete', ['book' => $chapter->book, 'chapter' => $chapter, 'current' => $chapter]);
}
/**
......@@ -148,11 +140,11 @@ class ChapterController extends Controller
*/
public function destroy($bookSlug, $chapterSlug)
{
$book = $this->bookRepo->getBySlug($bookSlug);
$chapter = $this->chapterRepo->getBySlug($chapterSlug, $book->id);
$chapter = $this->entityRepo->getBySlug('chapter', $chapterSlug, $bookSlug);
$book = $chapter->book;
$this->checkOwnablePermission('chapter-delete', $chapter);
Activity::addMessage('chapter_delete', $book->id, $chapter->name);
$this->chapterRepo->destroy($chapter);
$this->entityRepo->destroyChapter($chapter);
return redirect($book->getUrl());
}
......@@ -164,12 +156,12 @@ class ChapterController extends Controller
* @throws \BookStack\Exceptions\NotFoundException
*/
public function showMove($bookSlug, $chapterSlug) {
$book = $this->bookRepo->getBySlug($bookSlug);
$chapter = $this->chapterRepo->getBySlug($chapterSlug, $book->id);
$chapter = $this->entityRepo->getBySlug('chapter', $chapterSlug, $bookSlug);
$this->setPageTitle(trans('entities.chapters_move_named', ['chapterName' => $chapter->getShortName()]));
$this->checkOwnablePermission('chapter-update', $chapter);
return view('chapters/move', [
'chapter' => $chapter,
'book' => $book
'book' => $chapter->book
]);
}
......@@ -182,8 +174,7 @@ class ChapterController extends Controller
* @throws \BookStack\Exceptions\NotFoundException
*/
public function move($bookSlug, $chapterSlug, Request $request) {
$book = $this->bookRepo->getBySlug($bookSlug);
$chapter = $this->chapterRepo->getBySlug($chapterSlug, $book->id);
$chapter = $this->entityRepo->getBySlug('chapter', $chapterSlug, $bookSlug);
$this->checkOwnablePermission('chapter-update', $chapter);
$entitySelection = $request->get('entity_selection', null);
......@@ -198,17 +189,17 @@ class ChapterController extends Controller
$parent = false;
if ($entityType == 'book') {
$parent = $this->bookRepo->getById($entityId);
$parent = $this->entityRepo->getById('book', $entityId);
}
if ($parent === false || $parent === null) {
session()->flash('The selected Book was not found');
session()->flash('error', trans('errors.selected_book_not_found'));
return redirect()->back();
}
$this->chapterRepo->changeBook($parent->id, $chapter, true);
$this->entityRepo->changeBook('chapter', $parent->id, $chapter, true);
Activity::add($chapter, 'chapter_move', $chapter->book->id);
session()->flash('success', sprintf('Chapter moved to "%s"', $parent->name));
session()->flash('success', trans('entities.chapter_move_success', ['bookName' => $parent->name]));
return redirect($chapter->getUrl());
}
......@@ -221,8 +212,7 @@ class ChapterController extends Controller
*/
public function showRestrict($bookSlug, $chapterSlug)
{
$book = $this->bookRepo->getBySlug($bookSlug);
$chapter = $this->chapterRepo->getBySlug($chapterSlug, $book->id);
$chapter = $this->entityRepo->getBySlug('chapter', $chapterSlug, $bookSlug);
$this->checkOwnablePermission('restrictions-manage', $chapter);
$roles = $this->userRepo->getRestrictableRoles();
return view('chapters/restrictions', [
......@@ -240,11 +230,10 @@ class ChapterController extends Controller
*/
public function restrict($bookSlug, $chapterSlug, Request $request)
{
$book = $this->bookRepo->getBySlug($bookSlug);
$chapter = $this->chapterRepo->getBySlug($chapterSlug, $book->id);
$chapter = $this->entityRepo->getBySlug('chapter', $chapterSlug, $bookSlug);
$this->checkOwnablePermission('restrictions-manage', $chapter);
$this->chapterRepo->updateEntityPermissionsFromRequest($request, $chapter);
session()->flash('success', 'Chapter Restrictions Updated');
$this->entityRepo->updateEntityPermissionsFromRequest($request, $chapter);
session()->flash('success', trans('entities.chapters_permissions_success'));
return redirect($chapter->getUrl());
}
}
......
......@@ -5,6 +5,7 @@ namespace BookStack\Http\Controllers;
use Activity;
use BookStack\Repos\EntityRepo;
use BookStack\Http\Requests;
use Illuminate\Http\Response;
use Views;
class HomeController extends Controller
......@@ -31,9 +32,9 @@ class HomeController extends Controller
$activity = Activity::latest(10);
$draftPages = $this->signedIn ? $this->entityRepo->getUserDraftPages(6) : [];
$recentFactor = count($draftPages) > 0 ? 0.5 : 1;
$recents = $this->signedIn ? Views::getUserRecentlyViewed(12*$recentFactor, 0) : $this->entityRepo->getRecentlyCreatedBooks(10*$recentFactor);
$recentlyCreatedPages = $this->entityRepo->getRecentlyCreatedPages(5);
$recentlyUpdatedPages = $this->entityRepo->getRecentlyUpdatedPages(5);
$recents = $this->signedIn ? Views::getUserRecentlyViewed(12*$recentFactor, 0) : $this->entityRepo->getRecentlyCreated('book', 10*$recentFactor);
$recentlyCreatedPages = $this->entityRepo->getRecentlyCreated('page', 5);
$recentlyUpdatedPages = $this->entityRepo->getRecentlyUpdated('page', 5);
return view('home', [
'activity' => $activity,
'recents' => $recents,
......@@ -43,4 +44,39 @@ class HomeController extends Controller
]);
}
/**
* Get a js representation of the current translations
* @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
*/
public function getTranslations() {
$locale = trans()->getLocale();
$cacheKey = 'GLOBAL_TRANSLATIONS_' . $locale;
if (cache()->has($cacheKey) && config('app.env') !== 'development') {
$resp = cache($cacheKey);
} else {
$translations = [
// Get only translations which might be used in JS
'common' => trans('common'),
'components' => trans('components'),
'entities' => trans('entities'),
'errors' => trans('errors')
];
if ($locale !== 'en') {
$enTrans = [
'common' => trans('common', [], null, 'en'),
'components' => trans('components', [], null, 'en'),
'entities' => trans('entities', [], null, 'en'),
'errors' => trans('errors', [], null, 'en')
];
$translations = array_replace_recursive($enTrans, $translations);
}
$resp = 'window.translations = ' . json_encode($translations);
cache()->put($cacheKey, $resp, 120);
}
return response($resp, 200, [
'Content-Type' => 'application/javascript'
]);
}
}
......
<?php namespace BookStack\Http\Controllers;
use BookStack\Exceptions\ImageUploadException;
use BookStack\Repos\EntityRepo;
use BookStack\Repos\ImageRepo;
use Illuminate\Filesystem\Filesystem as File;
use Illuminate\Http\Request;
......@@ -73,6 +74,7 @@ class ImageController extends Controller
* @param $filter
* @param int $page
* @param Request $request
* @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
*/
public function getGalleryFiltered($filter, $page = 0, Request $request)
{
......@@ -149,12 +151,12 @@ class ImageController extends Controller
/**
* Deletes an image and all thumbnail/image files
* @param PageRepo $pageRepo
* @param EntityRepo $entityRepo
* @param Request $request
* @param int $id
* @return \Illuminate\Http\JsonResponse
*/
public function destroy(PageRepo $pageRepo, Request $request, $id)
public function destroy(EntityRepo $entityRepo, Request $request, $id)
{
$image = $this->imageRepo->getById($id);
$this->checkOwnablePermission('image-delete', $image);
......@@ -162,14 +164,14 @@ class ImageController extends Controller
// Check if this image is used on any pages
$isForced = ($request->has('force') && ($request->get('force') === 'true') || $request->get('force') === true);
if (!$isForced) {
$pageSearch = $pageRepo->searchForImage($image->url);
$pageSearch = $entityRepo->searchForImage($image->url);
if ($pageSearch !== false) {
return response()->json($pageSearch, 400);
}
}
$this->imageRepo->destroyImage($image);
return response()->json('Image Deleted');
return response()->json(trans('components.images_deleted'));
}
......
......@@ -2,9 +2,7 @@
use BookStack\Exceptions\PermissionsException;
use BookStack\Repos\PermissionsRepo;
use BookStack\Services\PermissionService;
use Illuminate\Http\Request;
use BookStack\Http\Requests;
class PermissionController extends Controller
{
......@@ -55,7 +53,7 @@ class PermissionController extends Controller
]);
$this->permissionsRepo->saveNewRole($request->all());
session()->flash('success', 'Role successfully created');
session()->flash('success', trans('settings.role_create_success'));
return redirect('/settings/roles');
}
......@@ -69,7 +67,7 @@ class PermissionController extends Controller
{
$this->checkPermission('user-roles-manage');
$role = $this->permissionsRepo->getRoleById($id);
if ($role->hidden) throw new PermissionsException('This role cannot be edited');
if ($role->hidden) throw new PermissionsException(trans('errors.role_cannot_be_edited'));
return view('settings/roles/edit', ['role' => $role]);
}
......@@ -88,7 +86,7 @@ class PermissionController extends Controller
]);
$this->permissionsRepo->updateRole($id, $request->all());
session()->flash('success', 'Role successfully updated');
session()->flash('success', trans('settings.role_update_success'));
return redirect('/settings/roles');
}
......@@ -103,7 +101,7 @@ class PermissionController extends Controller
$this->checkPermission('user-roles-manage');
$role = $this->permissionsRepo->getRoleById($id);
$roles = $this->permissionsRepo->getAllRolesExcept($role);
$blankRole = $role->newInstance(['display_name' => 'Don\'t migrate users']);
$blankRole = $role->newInstance(['display_name' => trans('settings.role_delete_no_migration')]);
$roles->prepend($blankRole);
return view('settings/roles/delete', ['role' => $role, 'roles' => $roles]);
}
......@@ -126,7 +124,7 @@ class PermissionController extends Controller
return redirect()->back();
}
session()->flash('success', 'Role successfully deleted');
session()->flash('success', trans('settings.role_delete_success'));
return redirect('/settings/roles');
}
}
......
<?php
namespace BookStack\Http\Controllers;
<?php namespace BookStack\Http\Controllers;
use BookStack\Repos\EntityRepo;
use BookStack\Services\ViewService;
use Illuminate\Http\Request;
use BookStack\Http\Requests;
use BookStack\Repos\BookRepo;
use BookStack\Repos\ChapterRepo;
use BookStack\Repos\PageRepo;
class SearchController extends Controller
{
protected $pageRepo;
protected $bookRepo;
protected $chapterRepo;
protected $entityRepo;
protected $viewService;
/**
* SearchController constructor.
* @param PageRepo $pageRepo
* @param BookRepo $bookRepo
* @param ChapterRepo $chapterRepo
* @param EntityRepo $entityRepo
* @param ViewService $viewService
*/
public function __construct(PageRepo $pageRepo, BookRepo $bookRepo, ChapterRepo $chapterRepo, ViewService $viewService)
public function __construct(EntityRepo $entityRepo, ViewService $viewService)
{
$this->pageRepo = $pageRepo;
$this->bookRepo = $bookRepo;
$this->chapterRepo = $chapterRepo;
$this->entityRepo = $entityRepo;
$this->viewService = $viewService;
parent::__construct();
}
......@@ -46,10 +34,10 @@ class SearchController extends Controller
}
$searchTerm = $request->get('term');
$paginationAppends = $request->only('term');
$pages = $this->pageRepo->getBySearch($searchTerm, [], 20, $paginationAppends);
$books = $this->bookRepo->getBySearch($searchTerm, 10, $paginationAppends);
$chapters = $this->chapterRepo->getBySearch($searchTerm, [], 10, $paginationAppends);
$this->setPageTitle('Search For ' . $searchTerm);
$pages = $this->entityRepo->getBySearch('page', $searchTerm, [], 20, $paginationAppends);
$books = $this->entityRepo->getBySearch('book', $searchTerm, [], 10, $paginationAppends);
$chapters = $this->entityRepo->getBySearch('chapter', $searchTerm, [], 10, $paginationAppends);
$this->setPageTitle(trans('entities.search_for_term', ['term' => $searchTerm]));
return view('search/all', [
'pages' => $pages,
'books' => $books,
......@@ -69,11 +57,11 @@ class SearchController extends Controller
$searchTerm = $request->get('term');
$paginationAppends = $request->only('term');
$pages = $this->pageRepo->getBySearch($searchTerm, [], 20, $paginationAppends);
$this->setPageTitle('Page Search For ' . $searchTerm);
$pages = $this->entityRepo->getBySearch('page', $searchTerm, [], 20, $paginationAppends);
$this->setPageTitle(trans('entities.search_page_for_term', ['term' => $searchTerm]));
return view('search/entity-search-list', [
'entities' => $pages,
'title' => 'Page Search Results',
'title' => trans('entities.search_results_page'),
'searchTerm' => $searchTerm
]);
}
......@@ -89,11 +77,11 @@ class SearchController extends Controller
$searchTerm = $request->get('term');
$paginationAppends = $request->only('term');
$chapters = $this->chapterRepo->getBySearch($searchTerm, [], 20, $paginationAppends);
$this->setPageTitle('Chapter Search For ' . $searchTerm);
$chapters = $this->entityRepo->getBySearch('chapter', $searchTerm, [], 20, $paginationAppends);
$this->setPageTitle(trans('entities.search_chapter_for_term', ['term' => $searchTerm]));
return view('search/entity-search-list', [
'entities' => $chapters,
'title' => 'Chapter Search Results',
'title' => trans('entities.search_results_chapter'),
'searchTerm' => $searchTerm
]);
}
......@@ -109,11 +97,11 @@ class SearchController extends Controller
$searchTerm = $request->get('term');
$paginationAppends = $request->only('term');
$books = $this->bookRepo->getBySearch($searchTerm, 20, $paginationAppends);
$this->setPageTitle('Book Search For ' . $searchTerm);
$books = $this->entityRepo->getBySearch('book', $searchTerm, [], 20, $paginationAppends);
$this->setPageTitle(trans('entities.search_book_for_term', ['term' => $searchTerm]));
return view('search/entity-search-list', [
'entities' => $books,
'title' => 'Book Search Results',
'title' => trans('entities.search_results_book'),
'searchTerm' => $searchTerm
]);
}
......@@ -132,8 +120,8 @@ class SearchController extends Controller
}
$searchTerm = $request->get('term');
$searchWhereTerms = [['book_id', '=', $bookId]];
$pages = $this->pageRepo->getBySearch($searchTerm, $searchWhereTerms);
$chapters = $this->chapterRepo->getBySearch($searchTerm, $searchWhereTerms);
$pages = $this->entityRepo->getBySearch('page', $searchTerm, $searchWhereTerms);
$chapters = $this->entityRepo->getBySearch('chapter', $searchTerm, $searchWhereTerms);
return view('search/book', ['pages' => $pages, 'chapters' => $chapters, 'searchTerm' => $searchTerm]);
}
......@@ -152,9 +140,11 @@ class SearchController extends Controller
// Search for entities otherwise show most popular
if ($searchTerm !== false) {
if ($entityTypes->contains('page')) $entities = $entities->merge($this->pageRepo->getBySearch($searchTerm)->items());
if ($entityTypes->contains('chapter')) $entities = $entities->merge($this->chapterRepo->getBySearch($searchTerm)->items());
if ($entityTypes->contains('book')) $entities = $entities->merge($this->bookRepo->getBySearch($searchTerm)->items());
foreach (['page', 'chapter', 'book'] as $entityType) {
if ($entityTypes->contains($entityType)) {
$entities = $entities->merge($this->entityRepo->getBySearch($entityType, $searchTerm)->items());
}
}
$entities = $entities->sortByDesc('title_relevance');
} else {
$entityNames = $entityTypes->map(function ($type) {
......
<?php namespace BookStack\Http\Controllers;
use Illuminate\Http\Request;
use BookStack\Http\Requests;
use Illuminate\Http\Response;
use Setting;
class SettingController extends Controller
......@@ -39,7 +38,7 @@ class SettingController extends Controller
Setting::put($key, $value);
}
session()->flash('success', 'Settings Saved');
session()->flash('success', trans('settings.settings_save_success'));
return redirect('/settings');
}
......
......@@ -2,7 +2,6 @@
use BookStack\Repos\TagRepo;
use Illuminate\Http\Request;
use BookStack\Http\Requests;
class TagController extends Controller
{
......@@ -16,12 +15,14 @@ class TagController extends Controller
public function __construct(TagRepo $tagRepo)
{
$this->tagRepo = $tagRepo;
parent::__construct();
}
/**
* Get all the Tags for a particular entity
* @param $entityType
* @param $entityId
* @return \Illuminate\Http\JsonResponse
*/
public function getForEntity($entityType, $entityId)
{
......@@ -30,28 +31,9 @@ class TagController extends Controller
}
/**
* Update the tags for a particular entity.
* @param $entityType
* @param $entityId
* @param Request $request
* @return mixed
*/
public function updateForEntity($entityType, $entityId, Request $request)
{
$entity = $this->tagRepo->getEntity($entityType, $entityId, 'update');
if ($entity === null) return $this->jsonError("Entity not found", 404);
$inputTags = $request->input('tags');
$tags = $this->tagRepo->saveTagsToEntity($entity, $inputTags);
return response()->json([
'tags' => $tags,
'message' => 'Tags successfully updated'
]);
}
/**
* Get tag name suggestions from a given search term.
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function getNameSuggestions(Request $request)
{
......@@ -63,6 +45,7 @@ class TagController extends Controller
/**
* Get tag value suggestions from a given search term.
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function getValueSuggestions(Request $request)
{
......
<?php
<?php namespace BookStack\Http\Controllers;
namespace BookStack\Http\Controllers;
use BookStack\Activity;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use BookStack\Http\Requests;
use BookStack\Repos\UserRepo;
use BookStack\Services\SocialAuthService;
use BookStack\User;
......@@ -44,7 +39,7 @@ class UserController extends Controller
'sort' => $request->has('sort') ? $request->get('sort') : 'name',
];
$users = $this->userRepo->getAllUsersPaginatedAndSorted(20, $listDetails);
$this->setPageTitle('Users');
$this->setPageTitle(trans('settings.users'));
$users->appends($listDetails);
return view('users/index', ['users' => $users, 'listDetails' => $listDetails]);
}
......@@ -83,7 +78,6 @@ class UserController extends Controller
}
$this->validate($request, $validationRules);
$user = $this->user->fill($request->all());
if ($authMethod === 'standard') {
......@@ -131,7 +125,7 @@ class UserController extends Controller
$authMethod = ($user->system_name) ? 'system' : config('auth.method');
$activeSocialDrivers = $socialAuthService->getActiveDrivers();
$this->setPageTitle('User Profile');
$this->setPageTitle(trans('settings.user_profile'));
$roles = $this->userRepo->getAllRoles();
return view('users/edit', ['user' => $user, 'activeSocialDrivers' => $activeSocialDrivers, 'authMethod' => $authMethod, 'roles' => $roles]);
}
......@@ -153,9 +147,8 @@ class UserController extends Controller
'name' => 'min:2',
'email' => 'min:2|email|unique:users,email,' . $id,
'password' => 'min:5|required_with:password_confirm',
'password-confirm' => 'same:password|required_with:password'
], [
'password-confirm.required_with' => 'Password confirmation required'
'password-confirm' => 'same:password|required_with:password',
'setting' => 'array'
]);
$user = $this->user->findOrFail($id);
......@@ -178,8 +171,15 @@ class UserController extends Controller
$user->external_auth_id = $request->get('external_auth_id');
}
// Save an user-specific settings
if ($request->has('setting')) {
foreach ($request->get('setting') as $key => $value) {
setting()->putUser($user, $key, $value);
}
}
$user->save();
session()->flash('success', 'User successfully updated');
session()->flash('success', trans('settings.users_edit_success'));
$redirectUrl = userCan('users-manage') ? '/settings/users' : '/settings/users/' . $user->id;
return redirect($redirectUrl);
......@@ -197,7 +197,7 @@ class UserController extends Controller
});
$user = $this->user->findOrFail($id);
$this->setPageTitle('Delete User ' . $user->name);
$this->setPageTitle(trans('settings.users_delete_named', ['userName' => $user->name]));
return view('users/delete', ['user' => $user]);
}
......@@ -216,17 +216,17 @@ class UserController extends Controller
$user = $this->userRepo->getById($id);
if ($this->userRepo->isOnlyAdmin($user)) {
session()->flash('error', 'You cannot delete the only admin');
session()->flash('error', trans('errors.users_cannot_delete_only_admin'));
return redirect($user->getEditUrl());
}
if ($user->system_name === 'public') {
session()->flash('error', 'You cannot delete the guest user');
session()->flash('error', trans('errors.users_cannot_delete_guest'));
return redirect($user->getEditUrl());
}
$this->userRepo->destroy($user);
session()->flash('success', 'User successfully removed');
session()->flash('success', trans('settings.users_delete_success'));
return redirect('/settings/users');
}
......
<?php
namespace BookStack\Http;
<?php namespace BookStack\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
......@@ -30,6 +28,7 @@ class Kernel extends HttpKernel
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\BookStack\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\BookStack\Http\Middleware\Localization::class
],
'api' => [
'throttle:60,1',
......
......@@ -4,8 +4,6 @@ namespace BookStack\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
use BookStack\Exceptions\UserRegistrationException;
use Setting;
class Authenticate
{
......
<?php namespace BookStack\Http\Middleware;
use Carbon\Carbon;
use Closure;
class Localization
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$defaultLang = config('app.locale');
$locale = setting()->getUser(user(), 'language', $defaultLang);
app()->setLocale($locale);
Carbon::setLocale($locale);
return $next($request);
}
}
<?php
namespace BookStack\Http\Middleware;
<?php namespace BookStack\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
......
......@@ -43,8 +43,9 @@ class ResetPassword extends Notification
public function toMail()
{
return (new MailMessage)
->line('You are receiving this email because we received a password reset request for your account.')
->action('Reset Password', baseUrl('password/reset/' . $this->token))
->line('If you did not request a password reset, no further action is required.');
->subject(trans('auth.email_reset_subject', ['appName' => setting('app-name')]))
->line(trans('auth.email_reset_text'))
->action(trans('auth.reset_password'), baseUrl('password/reset/' . $this->token))
->line(trans('auth.email_reset_not_requested'));
}
}
......
......@@ -7,6 +7,10 @@ class Page extends Entity
protected $simpleAttributes = ['name', 'id', 'slug'];
protected $with = ['book'];
protected $fieldsToSearch = ['name', 'text'];
/**
* Converts this page into a simplified array.
* @return mixed
......
<?php namespace BookStack\Providers;
use Illuminate\Support\ServiceProvider;
use Validator;
class AppServiceProvider extends ServiceProvider
{
......@@ -12,11 +13,10 @@ class AppServiceProvider extends ServiceProvider
public function boot()
{
// Custom validation methods
\Validator::extend('is_image', function($attribute, $value, $parameters, $validator) {
Validator::extend('is_image', function($attribute, $value, $parameters, $validator) {
$imageMimes = ['image/png', 'image/bmp', 'image/gif', 'image/jpeg', 'image/jpg', 'image/tiff', 'image/webp'];
return in_array($value->getMimeType(), $imageMimes);
});
}
/**
......
<?php namespace BookStack\Repos;
use Alpha\B;
use BookStack\Exceptions\NotFoundException;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Str;
use BookStack\Book;
use Views;
class BookRepo extends EntityRepo
{
protected $pageRepo;
protected $chapterRepo;
/**
* BookRepo constructor.
* @param PageRepo $pageRepo
* @param ChapterRepo $chapterRepo
*/
public function __construct(PageRepo $pageRepo, ChapterRepo $chapterRepo)
{
$this->pageRepo = $pageRepo;
$this->chapterRepo = $chapterRepo;
parent::__construct();
}
/**
* Base query for getting books.
* Takes into account any restrictions.
* @return mixed
*/
private function bookQuery()
{
return $this->permissionService->enforceBookRestrictions($this->book, 'view');
}
/**
* Get the book that has the given id.
* @param $id
* @return mixed
*/
public function getById($id)
{
return $this->bookQuery()->findOrFail($id);
}
/**
* Get all books, Limited by count.
* @param int $count
* @return mixed
*/
public function getAll($count = 10)
{
$bookQuery = $this->bookQuery()->orderBy('name', 'asc');
if (!$count) return $bookQuery->get();
return $bookQuery->take($count)->get();
}
/**
* Get all books paginated.
* @param int $count
* @return mixed
*/
public function getAllPaginated($count = 10)
{
return $this->bookQuery()
->orderBy('name', 'asc')->paginate($count);
}
/**
* Get the latest books.
* @param int $count
* @return mixed
*/
public function getLatest($count = 10)
{
return $this->bookQuery()->orderBy('created_at', 'desc')->take($count)->get();
}
/**
* Gets the most recently viewed for a user.
* @param int $count
* @param int $page
* @return mixed
*/
public function getRecentlyViewed($count = 10, $page = 0)
{
return Views::getUserRecentlyViewed($count, $page, $this->book);
}
/**
* Gets the most viewed books.
* @param int $count
* @param int $page
* @return mixed
*/
public function getPopular($count = 10, $page = 0)
{
return Views::getPopular($count, $page, $this->book);
}
/**
* Get a book by slug
* @param $slug
* @return mixed
* @throws NotFoundException
*/
public function getBySlug($slug)
{
$book = $this->bookQuery()->where('slug', '=', $slug)->first();
if ($book === null) throw new NotFoundException('Book not found');
return $book;
}
/**
* Checks if a book exists.
* @param $id
* @return bool
*/
public function exists($id)
{
return $this->bookQuery()->where('id', '=', $id)->exists();
}
/**
* Get a new book instance from request input.
* @param array $input
* @return Book
*/
public function createFromInput($input)
{
$book = $this->book->newInstance($input);
$book->slug = $this->findSuitableSlug($book->name);
$book->created_by = user()->id;
$book->updated_by = user()->id;
$book->save();
$this->permissionService->buildJointPermissionsForEntity($book);
return $book;
}
/**
* Update the given book from user input.
* @param Book $book
* @param $input
* @return Book
*/
public function updateFromInput(Book $book, $input)
{
if ($book->name !== $input['name']) {
$book->slug = $this->findSuitableSlug($input['name'], $book->id);
}
$book->fill($input);
$book->updated_by = user()->id;
$book->save();
$this->permissionService->buildJointPermissionsForEntity($book);
return $book;
}
/**
* Destroy the given book.
* @param Book $book
* @throws \Exception
*/
public function destroy(Book $book)
{
foreach ($book->pages as $page) {
$this->pageRepo->destroy($page);
}
foreach ($book->chapters as $chapter) {
$this->chapterRepo->destroy($chapter);
}
$book->views()->delete();
$book->permissions()->delete();
$this->permissionService->deleteJointPermissionsForEntity($book);
$book->delete();
}
/**
* Get the next child element priority.
* @param Book $book
* @return int
*/
public function getNewPriority($book)
{
$lastElem = $this->getChildren($book)->pop();
return $lastElem ? $lastElem->priority + 1 : 0;
}
/**
* @param string $slug
* @param bool|false $currentId
* @return bool
*/
public function doesSlugExist($slug, $currentId = false)
{
$query = $this->book->where('slug', '=', $slug);
if ($currentId) {
$query = $query->where('id', '!=', $currentId);
}
return $query->count() > 0;
}
/**
* Provides a suitable slug for the given book name.
* Ensures the returned slug is unique in the system.
* @param string $name
* @param bool|false $currentId
* @return string
*/
public function findSuitableSlug($name, $currentId = false)
{
$slug = $this->nameToSlug($name);
while ($this->doesSlugExist($slug, $currentId)) {
$slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
}
return $slug;
}
/**
* Get all child objects of a book.
* Returns a sorted collection of Pages and Chapters.
* Loads the book slug onto child elements to prevent access database access for getting the slug.
* @param Book $book
* @param bool $filterDrafts
* @return mixed
*/
public function getChildren(Book $book, $filterDrafts = false)
{
$pageQuery = $book->pages()->where('chapter_id', '=', 0);
$pageQuery = $this->permissionService->enforcePageRestrictions($pageQuery, 'view');
if ($filterDrafts) {
$pageQuery = $pageQuery->where('draft', '=', false);
}
$pages = $pageQuery->get();
$chapterQuery = $book->chapters()->with(['pages' => function ($query) use ($filterDrafts) {
$this->permissionService->enforcePageRestrictions($query, 'view');
if ($filterDrafts) $query->where('draft', '=', false);
}]);
$chapterQuery = $this->permissionService->enforceChapterRestrictions($chapterQuery, 'view');
$chapters = $chapterQuery->get();
$children = $pages->values();
foreach ($chapters as $chapter) {
$children->push($chapter);
}
$bookSlug = $book->slug;
$children->each(function ($child) use ($bookSlug) {
$child->setAttribute('bookSlug', $bookSlug);
if ($child->isA('chapter')) {
$child->pages->each(function ($page) use ($bookSlug) {
$page->setAttribute('bookSlug', $bookSlug);
});
$child->pages = $child->pages->sortBy(function ($child, $key) {
$score = $child->priority;
if ($child->draft) $score -= 100;
return $score;
});
}
});
// Sort items with drafts first then by priority.
return $children->sortBy(function ($child, $key) {
$score = $child->priority;
if ($child->isA('page') && $child->draft) $score -= 100;
return $score;
});
}
/**
* Get books by search term.
* @param $term
* @param int $count
* @param array $paginationAppends
* @return mixed
*/
public function getBySearch($term, $count = 20, $paginationAppends = [])
{
$terms = $this->prepareSearchTerms($term);
$bookQuery = $this->permissionService->enforceBookRestrictions($this->book->fullTextSearchQuery(['name', 'description'], $terms));
$bookQuery = $this->addAdvancedSearchQueries($bookQuery, $term);
$books = $bookQuery->paginate($count)->appends($paginationAppends);
$words = join('|', explode(' ', preg_quote(trim($term), '/')));
foreach ($books as $book) {
//highlight
$result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $book->getExcerpt(100));
$book->searchSnippet = $result;
}
return $books;
}
}
\ No newline at end of file
<?php namespace BookStack\Repos;
use Activity;
use BookStack\Book;
use BookStack\Exceptions\NotFoundException;
use Illuminate\Support\Str;
use BookStack\Chapter;
class ChapterRepo extends EntityRepo
{
protected $pageRepo;
/**
* ChapterRepo constructor.
* @param $pageRepo
*/
public function __construct(PageRepo $pageRepo)
{
$this->pageRepo = $pageRepo;
parent::__construct();
}
/**
* Base query for getting chapters, Takes permissions into account.
* @return mixed
*/
private function chapterQuery()
{
return $this->permissionService->enforceChapterRestrictions($this->chapter, 'view');
}
/**
* Check if an id exists.
* @param $id
* @return bool
*/
public function idExists($id)
{
return $this->chapterQuery()->where('id', '=', $id)->count() > 0;
}
/**
* Get a chapter by a specific id.
* @param $id
* @return mixed
*/
public function getById($id)
{
return $this->chapterQuery()->findOrFail($id);
}
/**
* Get all chapters.
* @return \Illuminate\Database\Eloquent\Collection|static[]
*/
public function getAll()
{
return $this->chapterQuery()->all();
}
/**
* Get a chapter that has the given slug within the given book.
* @param $slug
* @param $bookId
* @return mixed
* @throws NotFoundException
*/
public function getBySlug($slug, $bookId)
{
$chapter = $this->chapterQuery()->where('slug', '=', $slug)->where('book_id', '=', $bookId)->first();
if ($chapter === null) throw new NotFoundException('Chapter not found');
return $chapter;
}
/**
* Get the child items for a chapter
* @param Chapter $chapter
*/
public function getChildren(Chapter $chapter)
{
$pages = $this->permissionService->enforcePageRestrictions($chapter->pages())->get();
// Sort items with drafts first then by priority.
return $pages->sortBy(function ($child, $key) {
$score = $child->priority;
if ($child->draft) $score -= 100;
return $score;
});
}
/**
* Create a new chapter from request input.
* @param $input
* @param Book $book
* @return Chapter
*/
public function createFromInput($input, Book $book)
{
$chapter = $this->chapter->newInstance($input);
$chapter->slug = $this->findSuitableSlug($chapter->name, $book->id);
$chapter->created_by = user()->id;
$chapter->updated_by = user()->id;
$chapter = $book->chapters()->save($chapter);
$this->permissionService->buildJointPermissionsForEntity($chapter);
return $chapter;
}
/**
* Destroy a chapter and its relations by providing its slug.
* @param Chapter $chapter
*/
public function destroy(Chapter $chapter)
{
if (count($chapter->pages) > 0) {
foreach ($chapter->pages as $page) {
$page->chapter_id = 0;
$page->save();
}
}
Activity::removeEntity($chapter);
$chapter->views()->delete();
$chapter->permissions()->delete();
$this->permissionService->deleteJointPermissionsForEntity($chapter);
$chapter->delete();
}
/**
* Check if a chapter's slug exists.
* @param $slug
* @param $bookId
* @param bool|false $currentId
* @return bool
*/
public function doesSlugExist($slug, $bookId, $currentId = false)
{
$query = $this->chapter->where('slug', '=', $slug)->where('book_id', '=', $bookId);
if ($currentId) {
$query = $query->where('id', '!=', $currentId);
}
return $query->count() > 0;
}
/**
* Finds a suitable slug for the provided name.
* Checks database to prevent duplicate slugs.
* @param $name
* @param $bookId
* @param bool|false $currentId
* @return string
*/
public function findSuitableSlug($name, $bookId, $currentId = false)
{
$slug = $this->nameToSlug($name);
while ($this->doesSlugExist($slug, $bookId, $currentId)) {
$slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
}
return $slug;
}
/**
* Get a new priority value for a new page to be added
* to the given chapter.
* @param Chapter $chapter
* @return int
*/
public function getNewPriority(Chapter $chapter)
{
$lastPage = $chapter->pages->last();
return $lastPage !== null ? $lastPage->priority + 1 : 0;
}
/**
* Get chapters by the given search term.
* @param string $term
* @param array $whereTerms
* @param int $count
* @param array $paginationAppends
* @return mixed
*/
public function getBySearch($term, $whereTerms = [], $count = 20, $paginationAppends = [])
{
$terms = $this->prepareSearchTerms($term);
$chapterQuery = $this->permissionService->enforceChapterRestrictions($this->chapter->fullTextSearchQuery(['name', 'description'], $terms, $whereTerms));
$chapterQuery = $this->addAdvancedSearchQueries($chapterQuery, $term);
$chapters = $chapterQuery->paginate($count)->appends($paginationAppends);
$words = join('|', explode(' ', preg_quote(trim($term), '/')));
foreach ($chapters as $chapter) {
//highlight
$result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $chapter->getExcerpt(100));
$chapter->searchSnippet = $result;
}
return $chapters;
}
/**
* Changes the book relation of this chapter.
* @param $bookId
* @param Chapter $chapter
* @param bool $rebuildPermissions
* @return Chapter
*/
public function changeBook($bookId, Chapter $chapter, $rebuildPermissions = false)
{
$chapter->book_id = $bookId;
// Update related activity
foreach ($chapter->activity as $activity) {
$activity->book_id = $bookId;
$activity->save();
}
$chapter->slug = $this->findSuitableSlug($chapter->name, $bookId, $chapter->id);
$chapter->save();
// Update all child pages
foreach ($chapter->pages as $page) {
$this->pageRepo->changeBook($bookId, $page);
}
// Update permissions if applicable
if ($rebuildPermissions) {
$chapter->load('book');
$this->permissionService->buildJointPermissionsForEntity($chapter->book);
}
return $chapter;
}
}
\ No newline at end of file
......@@ -93,7 +93,7 @@ class PermissionsRepo
$permissions = isset($roleData['permissions']) ? array_keys($roleData['permissions']) : [];
$this->assignRolePermissions($role, $permissions);
if ($role->name === 'admin') {
if ($role->system_name === 'admin') {
$permissions = $this->permission->all()->pluck('id')->toArray();
$role->permissions()->sync($permissions);
}
......@@ -133,9 +133,9 @@ class PermissionsRepo
// Prevent deleting admin role or default registration role.
if ($role->system_name && in_array($role->system_name, $this->systemRoles)) {
throw new PermissionsException('This role is a system role and cannot be deleted');
throw new PermissionsException(trans('errors.role_system_cannot_be_deleted'));
} else if ($role->id == setting('registration-role')) {
throw new PermissionsException('This role cannot be deleted while set as the default registration role.');
throw new PermissionsException(trans('errors.role_registration_default_cannot_delete'));
}
if ($migrateRoleId) {
......
......@@ -38,7 +38,7 @@ class TagRepo
{
$entityInstance = $this->entity->getEntityInstance($entityType);
$searchQuery = $entityInstance->where('id', '=', $entityId)->with('tags');
$searchQuery = $this->permissionService->enforceEntityRestrictions($searchQuery, $action);
$searchQuery = $this->permissionService->enforceEntityRestrictions($entityType, $searchQuery, $action);
return $searchQuery->first();
}
......@@ -121,7 +121,7 @@ class TagRepo
/**
* Create a new Tag instance from user input.
* @param $input
* @return static
* @return Tag
*/
protected function newInstanceFromInput($input)
{
......
......@@ -3,7 +3,6 @@
use BookStack\Role;
use BookStack\User;
use Exception;
use Setting;
class UserRepo
{
......@@ -169,13 +168,13 @@ class UserRepo
public function getRecentlyCreated(User $user, $count = 20)
{
return [
'pages' => $this->entityRepo->getRecentlyCreatedPages($count, 0, function ($query) use ($user) {
'pages' => $this->entityRepo->getRecentlyCreated('page', $count, 0, function ($query) use ($user) {
$query->where('created_by', '=', $user->id);
}),
'chapters' => $this->entityRepo->getRecentlyCreatedChapters($count, 0, function ($query) use ($user) {
'chapters' => $this->entityRepo->getRecentlyCreated('chapter', $count, 0, function ($query) use ($user) {
$query->where('created_by', '=', $user->id);
}),
'books' => $this->entityRepo->getRecentlyCreatedBooks($count, 0, function ($query) use ($user) {
'books' => $this->entityRepo->getRecentlyCreated('book', $count, 0, function ($query) use ($user) {
$query->where('created_by', '=', $user->id);
})
];
......
......@@ -114,7 +114,7 @@ class ActivityService
$activity = $this->permissionService
->filterRestrictedEntityRelations($query, 'activities', 'entity_id', 'entity_type')
->orderBy('created_at', 'desc')->skip($count * $page)->take($count)->get();
->orderBy('created_at', 'desc')->with(['entity', 'user.avatar'])->skip($count * $page)->take($count)->get();
return $this->filterSimilar($activity);
}
......
......@@ -193,7 +193,7 @@ class AttachmentService extends UploadService
try {
$storage->put($attachmentStoragePath, $attachmentData);
} catch (Exception $e) {
throw new FileUploadException('File path ' . $attachmentStoragePath . ' could not be uploaded to. Ensure it is writable to the server.');
throw new FileUploadException(trans('errors.path_not_writable', ['filePath' => $attachmentStoragePath]));
}
return $attachmentPath;
}
......
......@@ -33,7 +33,7 @@ class EmailConfirmationService
public function sendConfirmation(User $user)
{
if ($user->email_confirmed) {
throw new ConfirmationEmailException('Email has already been confirmed, Try logging in.', '/login');
throw new ConfirmationEmailException(trans('errors.email_already_confirmed'), '/login');
}
$this->deleteConfirmationsByUser($user);
......@@ -63,7 +63,7 @@ class EmailConfirmationService
* Gets an email confirmation by looking up the token,
* Ensures the token has not expired.
* @param string $token
* @return EmailConfirmation
* @return array|null|\stdClass
* @throws UserRegistrationException
*/
public function getEmailConfirmationFromToken($token)
......@@ -72,14 +72,14 @@ class EmailConfirmationService
// If not found show error
if ($emailConfirmation === null) {
throw new UserRegistrationException('This confirmation token is not valid or has already been used, Please try registering again.', '/register');
throw new UserRegistrationException(trans('errors.email_confirmation_invalid'), '/register');
}
// If more than a day old
if (Carbon::now()->subDay()->gt(new Carbon($emailConfirmation->created_at))) {
$user = $this->users->getById($emailConfirmation->user_id);
$this->sendConfirmation($user);
throw new UserRegistrationException('The confirmation token has expired, A new confirmation email has been sent.', '/register/confirm');
throw new UserRegistrationException(trans('errors.email_confirmation_expired'), '/register/confirm');
}
$emailConfirmation->user = $this->users->getById($emailConfirmation->user_id);
......
<?php namespace BookStack\Services;
use BookStack\Page;
use BookStack\Repos\EntityRepo;
class ExportService
{
protected $entityRepo;
/**
* ExportService constructor.
* @param $entityRepo
*/
public function __construct(EntityRepo $entityRepo)
{
$this->entityRepo = $entityRepo;
}
/**
* Convert a page to a self-contained HTML file.
* Includes required CSS & image content. Images are base64 encoded into the HTML.
......@@ -15,7 +26,7 @@ class ExportService
public function pageToContainedHtml(Page $page)
{
$cssContent = file_get_contents(public_path('/css/export-styles.css'));
$pageHtml = view('pages/export', ['page' => $page, 'css' => $cssContent])->render();
$pageHtml = view('pages/export', ['page' => $page, 'pageContent' => $this->entityRepo->renderPage($page), 'css' => $cssContent])->render();
return $this->containHtml($pageHtml);
}
......@@ -27,9 +38,15 @@ class ExportService
public function pageToPdf(Page $page)
{
$cssContent = file_get_contents(public_path('/css/export-styles.css'));
$pageHtml = view('pages/pdf', ['page' => $page, 'css' => $cssContent])->render();
$pageHtml = view('pages/pdf', ['page' => $page, 'pageContent' => $this->entityRepo->renderPage($page), 'css' => $cssContent])->render();
// return $pageHtml;
$useWKHTML = config('snappy.pdf.binary') !== false;
$containedHtml = $this->containHtml($pageHtml);
$pdf = \PDF::loadHTML($containedHtml);
if ($useWKHTML) {
$pdf = \SnappyPDF::loadHTML($containedHtml);
} else {
$pdf = \PDF::loadHTML($containedHtml);
}
return $pdf->output();
}
......@@ -55,9 +72,13 @@ class ExportService
$pathString = $srcString;
}
if ($isLocal && !file_exists($pathString)) continue;
$imageContent = file_get_contents($pathString);
$imageEncoded = 'data:image/' . pathinfo($pathString, PATHINFO_EXTENSION) . ';base64,' . base64_encode($imageContent);
$newImageString = str_replace($srcString, $imageEncoded, $oldImgString);
try {
$imageContent = file_get_contents($pathString);
$imageEncoded = 'data:image/' . pathinfo($pathString, PATHINFO_EXTENSION) . ';base64,' . base64_encode($imageContent);
$newImageString = str_replace($srcString, $imageEncoded, $oldImgString);
} catch (\ErrorException $e) {
$newImageString = '';
}
$htmlContent = str_replace($oldImgString, $newImageString, $htmlContent);
}
}
......@@ -84,14 +105,14 @@ class ExportService
/**
* Converts the page contents into simple plain text.
* This method filters any bad looking content to
* provide a nice final output.
* This method filters any bad looking content to provide a nice final output.
* @param Page $page
* @return mixed
*/
public function pageToPlainText(Page $page)
{
$text = $page->text;
$html = $this->entityRepo->renderPage($page);
$text = strip_tags($html);
// Replace multiple spaces with single spaces
$text = preg_replace('/\ {2,}/', ' ', $text);
// Reduce multiple horrid whitespace characters.
......
......@@ -59,7 +59,7 @@ class ImageService extends UploadService
{
$imageName = $imageName ? $imageName : basename($url);
$imageData = file_get_contents($url);
if($imageData === false) throw new \Exception('Cannot get image from ' . $url);
if($imageData === false) throw new \Exception(trans('errors.cannot_get_image_from_url', ['url' => $url]));
return $this->saveNew($imageName, $imageData, $type);
}
......@@ -93,7 +93,7 @@ class ImageService extends UploadService
$storage->put($fullPath, $imageData);
$storage->setVisibility($fullPath, 'public');
} catch (Exception $e) {
throw new ImageUploadException('Image Path ' . $fullPath . ' is not writable by the server.');
throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
}
if ($this->isLocal()) $fullPath = str_replace_first('/public', '', $fullPath);
......@@ -160,7 +160,7 @@ class ImageService extends UploadService
$thumb = $this->imageTool->make($storage->get($imagePath));
} catch (Exception $e) {
if ($e instanceof \ErrorException || $e instanceof NotSupportedException) {
throw new ImageUploadException('The server cannot create thumbnails. Please check you have the GD PHP extension installed.');
throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
} else {
throw $e;
}
......
......@@ -94,4 +94,4 @@ class Ldap
return ldap_bind($ldapConnection, $bindRdn, $bindPassword);
}
}
\ No newline at end of file
}
......
......@@ -94,7 +94,7 @@ class LdapService
$ldapBind = $this->ldap->bind($connection, $ldapDn, $ldapPass);
}
if (!$ldapBind) throw new LdapException('LDAP access failed using ' . ($isAnonymous ? ' anonymous bind.' : ' given dn & pass details'));
if (!$ldapBind) throw new LdapException(($isAnonymous ? trans('errors.ldap_fail_anonymous') : trans('errors.ldap_fail_authed')));
}
/**
......@@ -109,15 +109,19 @@ class LdapService
// Check LDAP extension in installed
if (!function_exists('ldap_connect') && config('app.env') !== 'testing') {
throw new LdapException('LDAP PHP extension not installed');
throw new LdapException(trans('errors.ldap_extension_not_installed'));
}
// Get port from server string if specified.
// Get port from server string and protocol if specified.
$ldapServer = explode(':', $this->config['server']);
$ldapConnection = $this->ldap->connect($ldapServer[0], count($ldapServer) > 1 ? $ldapServer[1] : 389);
$hasProtocol = preg_match('/^ldaps{0,1}\:\/\//', $this->config['server']) === 1;
if (!$hasProtocol) array_unshift($ldapServer, '');
$hostName = $ldapServer[0] . ($hasProtocol?':':'') . $ldapServer[1];
$defaultPort = $ldapServer[0] === 'ldaps' ? 636 : 389;
$ldapConnection = $this->ldap->connect($hostName, count($ldapServer) > 2 ? intval($ldapServer[2]) : $defaultPort);
if ($ldapConnection === false) {
throw new LdapException('Cannot connect to ldap server, Initial connection failed');
throw new LdapException(trans('errors.ldap_cannot_connect'));
}
// Set any required options
......
......@@ -8,8 +8,9 @@ use BookStack\Ownable;
use BookStack\Page;
use BookStack\Role;
use BookStack\User;
use Illuminate\Database\Connection;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
class PermissionService
{
......@@ -23,6 +24,8 @@ class PermissionService
public $chapter;
public $page;
protected $db;
protected $jointPermission;
protected $role;
......@@ -31,18 +34,21 @@ class PermissionService
/**
* PermissionService constructor.
* @param JointPermission $jointPermission
* @param Connection $db
* @param Book $book
* @param Chapter $chapter
* @param Page $page
* @param Role $role
*/
public function __construct(JointPermission $jointPermission, Book $book, Chapter $chapter, Page $page, Role $role)
public function __construct(JointPermission $jointPermission, Connection $db, Book $book, Chapter $chapter, Page $page, Role $role)
{
$this->db = $db;
$this->jointPermission = $jointPermission;
$this->role = $role;
$this->book = $book;
$this->chapter = $chapter;
$this->page = $page;
// TODO - Update so admin still goes through filters
}
/**
......@@ -151,7 +157,7 @@ class PermissionService
*/
public function buildJointPermissionsForEntity(Entity $entity)
{
$roles = $this->role->with('jointPermissions')->get();
$roles = $this->role->get();
$entities = collect([$entity]);
if ($entity->isA('book')) {
......@@ -171,7 +177,7 @@ class PermissionService
*/
public function buildJointPermissionsForEntities(Collection $entities)
{
$roles = $this->role->with('jointPermissions')->get();
$roles = $this->role->get();
$this->deleteManyJointPermissionsForEntities($entities);
$this->createManyJointPermissions($entities, $roles);
}
......@@ -302,6 +308,10 @@ class PermissionService
$explodedAction = explode('-', $action);
$restrictionAction = end($explodedAction);
if ($role->system_name === 'admin') {
return $this->createJointPermissionDataArray($entity, $role, $action, true, true);
}
if ($entity->isA('book')) {
if (!$entity->restricted) {
......@@ -395,7 +405,7 @@ class PermissionService
$action = end($explodedPermission);
$this->currentAction = $action;
$nonJointPermissions = ['restrictions'];
$nonJointPermissions = ['restrictions', 'image', 'attachment'];
// Handle non entity specific jointPermissions
if (in_array($explodedPermission[0], $nonJointPermissions)) {
......@@ -411,7 +421,6 @@ class PermissionService
$this->currentAction = $permission;
}
$q = $this->entityRestrictionQuery($baseQuery)->count() > 0;
$this->clean();
return $q;
......@@ -462,60 +471,67 @@ class PermissionService
}
/**
* Add restrictions for a page query
* @param $query
* @param string $action
* @return mixed
* Get the children of a book in an efficient single query, Filtered by the permission system.
* @param integer $book_id
* @param bool $filterDrafts
* @return \Illuminate\Database\Query\Builder
*/
public function enforcePageRestrictions($query, $action = 'view')
{
// Prevent drafts being visible to others.
$query = $query->where(function ($query) {
$query->where('draft', '=', false);
if ($this->currentUser()) {
$query->orWhere(function ($query) {
$query->where('draft', '=', true)->where('created_by', '=', $this->currentUser()->id);
public function bookChildrenQuery($book_id, $filterDrafts = false) {
$pageSelect = $this->db->table('pages')->selectRaw("'BookStack\\\\Page' as entity_type, id, slug, name, text, '' as description, book_id, priority, chapter_id, draft")->where('book_id', '=', $book_id)->where(function($query) use ($filterDrafts) {
$query->where('draft', '=', 0);
if (!$filterDrafts) {
$query->orWhere(function($query) {
$query->where('draft', '=', 1)->where('created_by', '=', $this->currentUser()->id);
});
}
});
$chapterSelect = $this->db->table('chapters')->selectRaw("'BookStack\\\\Chapter' as entity_type, id, slug, name, '' as text, description, book_id, priority, 0 as chapter_id, 0 as draft")->where('book_id', '=', $book_id);
$query = $this->db->query()->select('*')->from($this->db->raw("({$pageSelect->toSql()} UNION {$chapterSelect->toSql()}) AS U"))
->mergeBindings($pageSelect)->mergeBindings($chapterSelect);
if (!$this->isAdmin()) {
$whereQuery = $this->db->table('joint_permissions as jp')->selectRaw('COUNT(*)')
->whereRaw('jp.entity_id=U.id')->whereRaw('jp.entity_type=U.entity_type')
->where('jp.action', '=', 'view')->whereIn('jp.role_id', $this->getRoles())
->where(function($query) {
$query->where('jp.has_permission', '=', 1)->orWhere(function($query) {
$query->where('jp.has_permission_own', '=', 1)->where('jp.created_by', '=', $this->currentUser()->id);
});
});
$query->whereRaw("({$whereQuery->toSql()}) > 0")->mergeBindings($whereQuery);
}
return $this->enforceEntityRestrictions($query, $action);
}
/**
* Add on permission restrictions to a chapter query.
* @param $query
* @param string $action
* @return mixed
*/
public function enforceChapterRestrictions($query, $action = 'view')
{
return $this->enforceEntityRestrictions($query, $action);
}
/**
* Add restrictions to a book query.
* @param $query
* @param string $action
* @return mixed
*/
public function enforceBookRestrictions($query, $action = 'view')
{
return $this->enforceEntityRestrictions($query, $action);
$query->orderBy('draft', 'desc')->orderBy('priority', 'asc');
$this->clean();
return $query;
}
/**
* Add restrictions for a generic entity
* @param $query
* @param string $entityType
* @param Builder|Entity $query
* @param string $action
* @return mixed
*/
public function enforceEntityRestrictions($query, $action = 'view')
public function enforceEntityRestrictions($entityType, $query, $action = 'view')
{
if (strtolower($entityType) === 'page') {
// Prevent drafts being visible to others.
$query = $query->where(function ($query) {
$query->where('draft', '=', false);
if ($this->currentUser()) {
$query->orWhere(function ($query) {
$query->where('draft', '=', true)->where('created_by', '=', $this->currentUser()->id);
});
}
});
}
if ($this->isAdmin()) {
$this->clean();
return $query;
}
$this->currentAction = $action;
return $this->entityRestrictionQuery($query);
}
......@@ -553,6 +569,7 @@ class PermissionService
});
});
});
$this->clean();
return $q;
}
......@@ -601,7 +618,7 @@ class PermissionService
private function isAdmin()
{
if ($this->isAdminUser === null) {
$this->isAdminUser = ($this->currentUser()->id !== null) ? $this->currentUser()->hasRole('admin') : false;
$this->isAdminUser = ($this->currentUser()->id !== null) ? $this->currentUser()->hasSystemRole('admin') : false;
}
return $this->isAdminUser;
......
<?php namespace BookStack\Services;
use BookStack\Setting;
use BookStack\User;
use Illuminate\Contracts\Cache\Repository as Cache;
/**
......@@ -38,11 +39,24 @@ class SettingService
*/
public function get($key, $default = false)
{
if ($default === false) $default = config('setting-defaults.' . $key, false);
$value = $this->getValueFromStore($key, $default);
return $this->formatValue($value, $default);
}
/**
* Get a user-specific setting from the database or cache.
* @param User $user
* @param $key
* @param bool $default
* @return bool|string
*/
public function getUser($user, $key, $default = false)
{
return $this->get($this->userKey($user->id, $key), $default);
}
/**
* Gets a setting value from the cache or database.
* Looks at the system defaults if not cached or in database.
* @param $key
......@@ -69,14 +83,6 @@ class SettingService
return $value;
}
// Check the defaults set in the app config.
$configPrefix = 'setting-defaults.' . $key;
if (config()->has($configPrefix)) {
$value = config($configPrefix);
$this->cache->forever($cacheKey, $value);
return $value;
}
return $default;
}
......@@ -119,6 +125,16 @@ class SettingService
}
/**
* Check if a user setting is in the database.
* @param $key
* @return bool
*/
public function hasUser($key)
{
return $this->has($this->userKey($key));
}
/**
* Add a setting to the database.
* @param $key
* @param $value
......@@ -136,6 +152,28 @@ class SettingService
}
/**
* Put a user-specific setting into the database.
* @param User $user
* @param $key
* @param $value
* @return bool
*/
public function putUser($user, $key, $value)
{
return $this->put($this->userKey($user->id, $key), $value);
}
/**
* Convert a setting key into a user-specific key.
* @param $key
* @return string
*/
protected function userKey($userId, $key = '')
{
return 'user:' . $userId . ':' . $key;
}
/**
* Removes a setting from the database.
* @param $key
* @return bool
......@@ -151,6 +189,16 @@ class SettingService
}
/**
* Delete settings for a given user id.
* @param $userId
* @return mixed
*/
public function deleteUserSettings($userId)
{
return $this->setting->where('setting_key', 'like', $this->userKey($userId) . '%')->delete();
}
/**
* Gets a setting model from the database for the given key.
* @param $key
* @return mixed
......
......@@ -70,12 +70,12 @@ class SocialAuthService
// Check social account has not already been used
if ($this->socialAccount->where('driver_id', '=', $socialUser->getId())->exists()) {
throw new UserRegistrationException('This ' . $socialDriver . ' account is already in use, Try logging in via the ' . $socialDriver . ' option.', '/login');
throw new UserRegistrationException(trans('errors.social_account_in_use', ['socialAccount'=>$socialDriver]), '/login');
}
if ($this->userRepo->getByEmail($socialUser->getEmail())) {
$email = $socialUser->getEmail();
throw new UserRegistrationException('The email ' . $email . ' is already in use. If you already have an account you can connect your ' . $socialDriver . ' account from your profile settings.', '/login');
throw new UserRegistrationException(trans('errors.social_account_in_use', ['socialAccount'=>$socialDriver, 'email' => $email]), '/login');
}
return $socialUser;
......@@ -98,7 +98,6 @@ class SocialAuthService
// Get any attached social accounts or users
$socialAccount = $this->socialAccount->where('driver_id', '=', $socialId)->first();
$user = $this->userRepo->getByEmail($socialUser->getEmail());
$isLoggedIn = auth()->check();
$currentUser = user();
......@@ -113,27 +112,26 @@ class SocialAuthService
if ($isLoggedIn && $socialAccount === null) {
$this->fillSocialAccount($socialDriver, $socialUser);
$currentUser->socialAccounts()->save($this->socialAccount);
session()->flash('success', title_case($socialDriver) . ' account was successfully attached to your profile.');
session()->flash('success', trans('settings.users_social_connected', ['socialAccount' => title_case($socialDriver)]));
return redirect($currentUser->getEditUrl());
}
// When a user is logged in and the social account exists and is already linked to the current user.
if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id === $currentUser->id) {
session()->flash('error', 'This ' . title_case($socialDriver) . ' account is already attached to your profile.');
session()->flash('error', trans('errors.social_account_existing', ['socialAccount' => title_case($socialDriver)]));
return redirect($currentUser->getEditUrl());
}
// When a user is logged in, A social account exists but the users do not match.
// Change the user that the social account is assigned to.
if ($isLoggedIn && $socialAccount !== null && $socialAccount->user->id != $currentUser->id) {
session()->flash('success', 'This ' . title_case($socialDriver) . ' account is already used by another user.');
session()->flash('error', trans('errors.social_account_already_used_existing', ['socialAccount' => title_case($socialDriver)]));
return redirect($currentUser->getEditUrl());
}
// Otherwise let the user know this social account is not used by anyone.
$message = 'This ' . $socialDriver . ' account is not linked to any users. Please attach it in your profile settings';
$message = trans('errors.social_account_not_used', ['socialAccount' => title_case($socialDriver)]);
if (setting('registration-enabled')) {
$message .= ' or, If you do not yet have an account, You can register an account using the ' . $socialDriver . ' option';
$message .= trans('errors.social_account_register_instructions', ['socialAccount' => title_case($socialDriver)]);
}
throw new SocialSignInException($message . '.', '/login');
......@@ -157,8 +155,8 @@ class SocialAuthService
{
$driver = trim(strtolower($socialDriver));
if (!in_array($driver, $this->validSocialDrivers)) abort(404, 'Social Driver Not Found');
if (!$this->checkDriverConfigured($driver)) throw new SocialDriverNotConfigured("Your {$driver} social settings are not configured correctly.");
if (!in_array($driver, $this->validSocialDrivers)) abort(404, trans('errors.social_driver_not_found'));
if (!$this->checkDriverConfigured($driver)) throw new SocialDriverNotConfigured(trans('errors.social_driver_not_configured', ['socialAccount' => title_case($socialDriver)]));
return $driver;
}
......@@ -215,7 +213,7 @@ class SocialAuthService
{
session();
user()->socialAccounts()->where('driver', '=', $socialDriver)->delete();
session()->flash('success', title_case($socialDriver) . ' account successfully detached');
session()->flash('success', trans('settings.users_social_disconnected', ['socialAccount' => title_case($socialDriver)]));
return redirect(user()->getEditUrl());
}
......
......@@ -5,9 +5,7 @@ use BookStack\View;
class ViewService
{
protected $view;
protected $user;
protected $permissionService;
/**
......@@ -18,7 +16,6 @@ class ViewService
public function __construct(View $view, PermissionService $permissionService)
{
$this->view = $view;
$this->user = user();
$this->permissionService = $permissionService;
}
......@@ -29,8 +26,9 @@ class ViewService
*/
public function add(Entity $entity)
{
if ($this->user === null) return 0;
$view = $entity->views()->where('user_id', '=', $this->user->id)->first();
$user = user();
if ($user === null || $user->isDefault()) return 0;
$view = $entity->views()->where('user_id', '=', $user->id)->first();
// Add view if model exists
if ($view) {
$view->increment('views');
......@@ -39,7 +37,7 @@ class ViewService
// Otherwise create new view count
$entity->views()->save($this->view->create([
'user_id' => $this->user->id,
'user_id' => $user->id,
'views' => 1
]));
......@@ -78,13 +76,14 @@ class ViewService
*/
public function getUserRecentlyViewed($count = 10, $page = 0, $filterModel = false)
{
if ($this->user === null) return collect();
$user = user();
if ($user === null || $user->isDefault()) return collect();
$query = $this->permissionService
->filterRestrictedEntityRelations($this->view, 'views', 'viewable_id', 'viewable_type');
if ($filterModel) $query = $query->where('viewable_type', '=', get_class($filterModel));
$query = $query->where('user_id', '=', user()->id);
$query = $query->where('user_id', '=', $user->id);
$viewables = $query->with('viewable')->orderBy('updated_at', 'desc')
->skip($count * $page)->take($count)->get()->pluck('viewable');
......
......@@ -75,6 +75,16 @@ class User extends Model implements AuthenticatableContract, CanResetPasswordCon
}
/**
* Check if the user has a role.
* @param $role
* @return mixed
*/
public function hasSystemRole($role)
{
return $this->roles->pluck('system_name')->contains('admin');
}
/**
* Get all permissions belonging to a the current user.
* @param bool $cache
* @return \Illuminate\Database\Eloquent\Relations\HasManyThrough
......@@ -150,8 +160,16 @@ class User extends Model implements AuthenticatableContract, CanResetPasswordCon
*/
public function getAvatar($size = 50)
{
if ($this->image_id === 0 || $this->image_id === '0' || $this->image_id === null) return baseUrl('/user_avatar.png');
return baseUrl($this->avatar->getThumb($size, $size, false));
$default = baseUrl('/user_avatar.png');
$imageId = $this->image_id;
if ($imageId === 0 || $imageId === '0' || $imageId === null) return $default;
try {
$avatar = baseUrl($this->avatar->getThumb($size, $size, false));
} catch (\Exception $err) {
$avatar = $default;
}
return $avatar;
}
/**
......
......@@ -60,11 +60,12 @@ function userCan($permission, Ownable $ownable = null)
* Helper to access system settings.
* @param $key
* @param bool $default
* @return mixed
* @return bool|string|\BookStack\Services\SettingService
*/
function setting($key, $default = false)
function setting($key = null, $default = false)
{
$settingService = app(\BookStack\Services\SettingService::class);
if (is_null($key)) return $settingService;
return $settingService->get($key, $default);
}
......
......@@ -15,7 +15,8 @@
"league/flysystem-aws-s3-v3": "^1.0",
"barryvdh/laravel-dompdf": "^0.7",
"predis/predis": "^1.1",
"gathercontent/htmldiff": "^0.2.1"
"gathercontent/htmldiff": "^0.2.1",
"barryvdh/laravel-snappy": "^0.3.1"
},
"require-dev": {
"fzaninotto/faker": "~1.4",
......
......@@ -4,8 +4,8 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"This file is @generated automatically"
],
"hash": "3124d900cfe857392a94de479f3ff6d4",
"content-hash": "a968767a73f77e66e865c276cf76eedf",
"hash": "2438a2f4a02adbea5f378f9e9408eb29",
"content-hash": "6add8bff71ecc86e0c90858590834a26",
"packages": [
{
"name": "aws/aws-sdk-php",
......@@ -256,6 +256,58 @@
"time": "2016-07-04 11:52:48"
},
{
"name": "barryvdh/laravel-snappy",
"version": "v0.3.1",
"source": {
"type": "git",
"url": "https://github.com/barryvdh/laravel-snappy.git",
"reference": "509a4497be63d8ee7ff464a3daf00d9edde08e21"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/barryvdh/laravel-snappy/zipball/509a4497be63d8ee7ff464a3daf00d9edde08e21",
"reference": "509a4497be63d8ee7ff464a3daf00d9edde08e21",
"shasum": ""
},
"require": {
"illuminate/filesystem": "5.0.x|5.1.x|5.2.x|5.3.x",
"illuminate/support": "5.0.x|5.1.x|5.2.x|5.3.x",
"knplabs/knp-snappy": "*",
"php": ">=5.4.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "0.3-dev"
}
},
"autoload": {
"psr-4": {
"Barryvdh\\Snappy\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Barry vd. Heuvel",
"email": "barryvdh@gmail.com"
}
],
"description": "Snappy PDF/Image for Laravel 4",
"keywords": [
"image",
"laravel",
"pdf",
"snappy",
"wkhtmltoimage",
"wkhtmltopdf"
],
"time": "2016-08-05 13:08:28"
},
{
"name": "barryvdh/reflection-docblock",
"version": "v2.0.4",
"source": {
......@@ -998,6 +1050,71 @@
"time": "2015-12-05 17:17:57"
},
{
"name": "knplabs/knp-snappy",
"version": "0.4.3",
"source": {
"type": "git",
"url": "https://github.com/KnpLabs/snappy.git",
"reference": "44f7a9b37d5686fd7db4c1e9569a802a5d16923f"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/KnpLabs/snappy/zipball/44f7a9b37d5686fd7db4c1e9569a802a5d16923f",
"reference": "44f7a9b37d5686fd7db4c1e9569a802a5d16923f",
"shasum": ""
},
"require": {
"php": ">=5.3.3",
"symfony/process": "~2.3|~3.0"
},
"require-dev": {
"phpunit/phpunit": "~4.7"
},
"suggest": {
"h4cc/wkhtmltoimage-amd64": "Provides wkhtmltoimage-amd64 binary for Linux-compatible machines, use version `~0.12` as dependency",
"h4cc/wkhtmltoimage-i386": "Provides wkhtmltoimage-i386 binary for Linux-compatible machines, use version `~0.12` as dependency",
"h4cc/wkhtmltopdf-amd64": "Provides wkhtmltopdf-amd64 binary for Linux-compatible machines, use version `~0.12` as dependency",
"h4cc/wkhtmltopdf-i386": "Provides wkhtmltopdf-i386 binary for Linux-compatible machines, use version `~0.12` as dependency",
"wemersonjanuario/wkhtmltopdf-windows": "Provides wkhtmltopdf executable for Windows, use version `~0.12` as dependency"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "0.5.x-dev"
}
},
"autoload": {
"psr-0": {
"Knp\\Snappy": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "KNPLabs Team",
"homepage": "http://knplabs.com"
},
{
"name": "Symfony Community",
"homepage": "http://github.com/KnpLabs/snappy/contributors"
}
],
"description": "PHP5 library allowing thumbnail, snapshot or PDF generation from a url or a html page. Wrapper for wkhtmltopdf/wkhtmltoimage.",
"homepage": "http://github.com/KnpLabs/snappy",
"keywords": [
"knp",
"knplabs",
"pdf",
"snapshot",
"thumbnail",
"wkhtmltopdf"
],
"time": "2015-11-17 13:16:27"
},
{
"name": "laravel/framework",
"version": "v5.3.11",
"source": {
......
......@@ -148,6 +148,7 @@ return [
Barryvdh\DomPDF\ServiceProvider::class,
Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class,
Barryvdh\Debugbar\ServiceProvider::class,
Barryvdh\Snappy\ServiceProvider::class,
/*
......@@ -218,6 +219,7 @@ return [
'ImageTool' => Intervention\Image\Facades\Image::class,
'PDF' => Barryvdh\DomPDF\Facade::class,
'SnappyPDF' => Barryvdh\Snappy\Facades\SnappyPdf::class,
'Debugbar' => Barryvdh\Debugbar\Facade::class,
/**
......
......@@ -6,6 +6,7 @@
return [
'app-name' => 'BookStack',
'app-logo' => '',
'app-name-header' => true,
'app-editor' => 'wysiwyg',
'app-color' => '#0288D1',
......
<?php
return [
'pdf' => [
'enabled' => true,
'binary' => file_exists(base_path('wkhtmltopdf')) ? base_path('wkhtmltopdf') : env('WKHTMLTOPDF', false),
'timeout' => false,
'options' => [],
'env' => [],
],
'image' => [
'enabled' => false,
'binary' => '/usr/local/bin/wkhtmltoimage',
'timeout' => false,
'options' => [],
'env' => [],
],
];
......@@ -59,4 +59,14 @@ $factory->define(BookStack\Tag::class, function ($faker) {
'name' => $faker->city,
'value' => $faker->sentence(3)
];
});
$factory->define(BookStack\Image::class, function ($faker) {
return [
'name' => $faker->slug . '.jpg',
'url' => $faker->url,
'path' => $faker->url,
'type' => 'gallery',
'uploaded_to' => 0
];
});
\ No newline at end of file
......
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCacheTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('cache', function (Blueprint $table) {
$table->string('key')->unique();
$table->text('value');
$table->integer('expiration');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('cache');
}
}
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSessionsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('sessions', function (Blueprint $table) {
$table->string('id')->unique();
$table->integer('user_id')->nullable();
$table->string('ip_address', 45)->nullable();
$table->text('user_agent')->nullable();
$table->text('payload');
$table->integer('last_activity');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('sessions');
}
}
{
"private": true,
"scripts": {
"prod": "gulp --production",
"dev": "gulp watch"
"build": "gulp --production",
"dev": "gulp watch",
"watch": "gulp watch"
},
"devDependencies": {
"angular": "^1.5.5",
......@@ -15,7 +16,9 @@
"laravel-elixir": "^6.0.0-11",
"laravel-elixir-browserify-official": "^0.1.3",
"marked": "^0.3.5",
"moment": "^2.12.0",
"zeroclipboard": "^2.2.0"
"moment": "^2.12.0"
},
"dependencies": {
"clipboard": "^1.5.16"
}
}
......
......@@ -22,6 +22,7 @@
<php>
<env name="APP_ENV" value="testing"/>
<env name="APP_DEBUG" value="false"/>
<env name="APP_LANG" value="en"/>
<env name="CACHE_DRIVER" value="array"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="QUEUE_DRIVER" value="sync"/>
......
No preview for this file type
......@@ -17,25 +17,42 @@ A platform for storing and organising information and documentation. General inf
All development on BookStack is currently done on the master branch. When it's time for a release the master branch is merged into release with built & minified CSS & JS then tagged at it's version. Here are the current development requirements:
* [Node.js](https://nodejs.org/en/)
* [Gulp](http://gulpjs.com/)
* [Node.js](https://nodejs.org/en/) v6.9+
SASS is used to help the CSS development and the JavaScript is run through browserify/babel to allow for writing ES6 code. Both of these are done using gulp.
SASS is used to help the CSS development and the JavaScript is run through browserify/babel to allow for writing ES6 code. Both of these are done using gulp. To run the build task you can use the following commands:
``` bash
# Build and minify for production
npm run-script build
# Build for dev (With sourcemaps) and watch for changes
npm run-script dev
```
BookStack has many integration tests that use Laravel's built-in testing capabilities which makes use of PHPUnit. To use you will need PHPUnit installed and accessible via command line. There is a `mysql_testing` database defined within the app config which is what is used by PHPUnit. This database is set with the following database name, user name and password defined as `bookstack-test`. You will have to create that database and credentials before testing.
The testing database will also need migrating and seeding beforehand. This can be done with the following commands:
```
``` bash
php artisan migrate --database=mysql_testing
php artisan db:seed --class=DummyContentSeeder --database=mysql_testing
```
Once done you can run `phpunit` in the application root directory to run all tests.
## Translations
As part of BookStack v0.14 support for translations has been built in. All text strings can be found in the `resources/lang` folder where each language option has its own folder. To add a new language you should copy the `en` folder to an new folder (eg. `fr` for french) then go through and translate all text strings in those files, leaving the keys and file-names intact. If a language string is missing then the `en` translation will be used. To show the language option in the user preferences language drop-down you will need to add your language to the options found at the bottom of the `resources/lang/en/settings.php` file. A system-wide language can also be set in the `.env` file like so: `APP_LANG=en`.
Some strings have colon-prefixed variables in such as `:userName`. Leave these values as they are as they will be replaced at run-time.
## Website, Docs & Blog
The website project docs & Blog can be found in the [BookStackApp/website](https://github.com/BookStackApp/website) repo.
## License
BookStack is provided under the MIT License.
The BookStack source is provided under the MIT License.
## Attribution
......@@ -53,5 +70,11 @@ These are the great projects used to help build BookStack:
* [TinyColorPicker](http://www.dematte.at/tinyColorPicker/index.html)
* [Marked](https://github.com/chjj/marked)
* [Moment.js](http://momentjs.com/)
* [BarryVD](https://github.com/barryvdh)
* [Debugbar](https://github.com/barryvdh/laravel-debugbar)
* [Dompdf](https://github.com/barryvdh/laravel-dompdf)
* [Snappy (WKHTML2PDF)](https://github.com/barryvdh/laravel-snappy)
* [Laravel IDE helper](https://github.com/barryvdh/laravel-ide-helper)
* [WKHTMLtoPDF](http://wkhtmltopdf.org/index.html)
Additionally, Thank you [BrowserStack](https://www.browserstack.com/) for supporting us and making cross-browser testing easy.
......
"use strict";
// AngularJS - Create application and load components
var angular = require('angular');
var ngResource = require('angular-resource');
var ngAnimate = require('angular-animate');
var ngSanitize = require('angular-sanitize');
require('angular-ui-sortable');
import angular from "angular";
import "angular-resource";
import "angular-animate";
import "angular-sanitize";
import "angular-ui-sortable";
// Url retrieval function
window.baseUrl = function(path) {
......@@ -15,7 +15,13 @@ window.baseUrl = function(path) {
return basePath + '/' + path;
};
var ngApp = angular.module('bookStack', ['ngResource', 'ngAnimate', 'ngSanitize', 'ui.sortable']);
let ngApp = angular.module('bookStack', ['ngResource', 'ngAnimate', 'ngSanitize', 'ui.sortable']);
// Translation setup
// Creates a global function with name 'trans' to be used in the same way as Laravel's translation system
import Translations from "./translations"
let translator = new Translations(window.translations);
window.trans = translator.get.bind(translator);
// Global Event System
class EventManager {
......@@ -25,9 +31,9 @@ class EventManager {
emit(eventName, eventData) {
if (typeof this.listeners[eventName] === 'undefined') return this;
var eventsToStart = this.listeners[eventName];
let eventsToStart = this.listeners[eventName];
for (let i = 0; i < eventsToStart.length; i++) {
var event = eventsToStart[i];
let event = eventsToStart[i];
event(eventData);
}
return this;
......@@ -55,10 +61,9 @@ Controllers(ngApp, window.Events);
// Smooth scrolling
jQuery.fn.smoothScrollTo = function () {
if (this.length === 0) return;
let scrollElem = document.documentElement.scrollTop === 0 ? document.body : document.documentElement;
$(scrollElem).animate({
$('html, body').animate({
scrollTop: this.offset().top - 60 // Adjust to change final scroll position top margin
}, 800); // Adjust to change animations speed (ms)
}, 300); // Adjust to change animations speed (ms)
return this;
};
......@@ -70,93 +75,83 @@ jQuery.expr[":"].contains = $.expr.createPseudo(function (arg) {
});
// Global jQuery Elements
$(function () {
var notifications = $('.notification');
var successNotification = notifications.filter('.pos');
var errorNotification = notifications.filter('.neg');
var warningNotification = notifications.filter('.warning');
// Notification Events
window.Events.listen('success', function (text) {
successNotification.hide();
successNotification.find('span').text(text);
let notifications = $('.notification');
let successNotification = notifications.filter('.pos');
let errorNotification = notifications.filter('.neg');
let warningNotification = notifications.filter('.warning');
// Notification Events
window.Events.listen('success', function (text) {
successNotification.hide();
successNotification.find('span').text(text);
setTimeout(() => {
successNotification.show();
}, 1);
});
window.Events.listen('warning', function (text) {
warningNotification.find('span').text(text);
warningNotification.show();
});
window.Events.listen('error', function (text) {
errorNotification.find('span').text(text);
errorNotification.show();
});
// Notification hiding
notifications.click(function () {
$(this).fadeOut(100);
});
// Chapter page list toggles
$('.chapter-toggle').click(function (e) {
e.preventDefault();
$(this).toggleClass('open');
$(this).closest('.chapter').find('.inset-list').slideToggle(180);
});
// Back to top button
$('#back-to-top').click(function() {
$('#header').smoothScrollTo();
});
let scrollTopShowing = false;
let scrollTop = document.getElementById('back-to-top');
let scrollTopBreakpoint = 1200;
window.addEventListener('scroll', function() {
let scrollTopPos = document.documentElement.scrollTop || document.body.scrollTop || 0;
if (!scrollTopShowing && scrollTopPos > scrollTopBreakpoint) {
scrollTop.style.display = 'block';
scrollTopShowing = true;
setTimeout(() => {
successNotification.show();
scrollTop.style.opacity = 0.4;
}, 1);
});
window.Events.listen('warning', function (text) {
warningNotification.find('span').text(text);
warningNotification.show();
});
window.Events.listen('error', function (text) {
errorNotification.find('span').text(text);
errorNotification.show();
});
// Notification hiding
notifications.click(function () {
$(this).fadeOut(100);
});
// Chapter page list toggles
$('.chapter-toggle').click(function (e) {
e.preventDefault();
$(this).toggleClass('open');
$(this).closest('.chapter').find('.inset-list').slideToggle(180);
});
// Back to top button
$('#back-to-top').click(function() {
$('#header').smoothScrollTo();
});
var scrollTopShowing = false;
var scrollTop = document.getElementById('back-to-top');
var scrollTopBreakpoint = 1200;
window.addEventListener('scroll', function() {
let scrollTopPos = document.documentElement.scrollTop || document.body.scrollTop || 0;
if (!scrollTopShowing && scrollTopPos > scrollTopBreakpoint) {
scrollTop.style.display = 'block';
scrollTopShowing = true;
setTimeout(() => {
scrollTop.style.opacity = 0.4;
}, 1);
} else if (scrollTopShowing && scrollTopPos < scrollTopBreakpoint) {
scrollTop.style.opacity = 0;
scrollTopShowing = false;
setTimeout(() => {
scrollTop.style.display = 'none';
}, 500);
}
});
// Common jQuery actions
$('[data-action="expand-entity-list-details"]').click(function() {
$('.entity-list.compact').find('p').not('.empty-text').slideToggle(240);
});
// Popup close
$('.popup-close').click(function() {
$(this).closest('.overlay').fadeOut(240);
});
$('.overlay').click(function(event) {
if (!$(event.target).hasClass('overlay')) return;
$(this).fadeOut(240);
});
// Prevent markdown display link click redirect
$('.markdown-display').on('click', 'a', function(event) {
event.preventDefault();
window.open($(this).attr('href'));
});
// Detect IE for css
if(navigator.userAgent.indexOf('MSIE')!==-1
|| navigator.appVersion.indexOf('Trident/') > 0
|| navigator.userAgent.indexOf('Safari') !== -1){
$('body').addClass('flexbox-support');
} else if (scrollTopShowing && scrollTopPos < scrollTopBreakpoint) {
scrollTop.style.opacity = 0;
scrollTopShowing = false;
setTimeout(() => {
scrollTop.style.display = 'none';
}, 500);
}
});
// Common jQuery actions
$('[data-action="expand-entity-list-details"]').click(function() {
$('.entity-list.compact').find('p').not('.empty-text').slideToggle(240);
});
// Popup close
$('.popup-close').click(function() {
$(this).closest('.overlay').fadeOut(240);
});
$('.overlay').click(function(event) {
if (!$(event.target).hasClass('overlay')) return;
$(this).fadeOut(240);
});
// Detect IE for css
if(navigator.userAgent.indexOf('MSIE')!==-1
|| navigator.appVersion.indexOf('Trident/') > 0
|| navigator.userAgent.indexOf('Safari') !== -1){
$('body').addClass('flexbox-support');
}
// Page specific items
require('./pages/page-show');
import "./pages/page-show";
......
"use strict";
// Configure ZeroClipboard
var zeroClipBoard = require('zeroclipboard');
zeroClipBoard.config({
swfPath: window.baseUrl('/ZeroClipboard.swf')
});
import Clipboard from "clipboard";
window.setupPageShow = module.exports = function (pageId) {
export default window.setupPageShow = function (pageId) {
// Set up pointer
var $pointer = $('#pointer').detach();
var $pointerInner = $pointer.children('div.pointer').first();
var isSelection = false;
let $pointer = $('#pointer').detach();
let pointerShowing = false;
let $pointerInner = $pointer.children('div.pointer').first();
let isSelection = false;
let pointerModeLink = true;
let pointerSectionId = '';
// Select all contents on input click
$pointer.on('click', 'input', function (e) {
......@@ -18,35 +18,53 @@ window.setupPageShow = module.exports = function (pageId) {
e.stopPropagation();
});
// Set up copy-to-clipboard
new zeroClipBoard($pointer.find('button').first()[0]);
// Pointer mode toggle
$pointer.on('click', 'span.icon', event => {
let $icon = $(event.currentTarget);
pointerModeLink = !pointerModeLink;
$icon.html(pointerModeLink ? '<i class="zmdi zmdi-link"></i>' : '<i class="zmdi zmdi-square-down"></i>');
updatePointerContent();
});
// Set up clipboard
let clipboard = new Clipboard('#pointer button');
// Hide pointer when clicking away
$(document.body).find('*').on('click focus', function (e) {
if (!isSelection) {
$pointer.detach();
}
$(document.body).find('*').on('click focus', event => {
if (!pointerShowing || isSelection) return;
let target = $(event.target);
if (target.is('.zmdi') || $(event.target).closest('#pointer').length === 1) return;
$pointer.detach();
pointerShowing = false;
});
function updatePointerContent() {
let inputText = pointerModeLink ? window.baseUrl(`/link/${pageId}#${pointerSectionId}`) : `{{@${pageId}#${pointerSectionId}}}`;
if (pointerModeLink && inputText.indexOf('http') !== 0) inputText = window.location.protocol + "//" + window.location.host + inputText;
$pointer.find('input').val(inputText);
}
// Show pointer when selecting a single block of tagged content
$('.page-content [id^="bkmrk"]').on('mouseup keyup', function (e) {
e.stopPropagation();
var selection = window.getSelection();
let selection = window.getSelection();
if (selection.toString().length === 0) return;
// Show pointer and set link
var $elem = $(this);
let link = window.baseUrl('/link/' + pageId + '#' + $elem.attr('id'));
if (link.indexOf('http') !== 0) link = window.location.protocol + "//" + window.location.host + link;
$pointer.find('input').val(link);
$pointer.find('button').first().attr('data-clipboard-text', link);
let $elem = $(this);
pointerSectionId = $elem.attr('id');
updatePointerContent();
$elem.before($pointer);
$pointer.show();
pointerShowing = true;
// Set pointer to sit near mouse-up position
var pointerLeftOffset = (e.pageX - $elem.offset().left - ($pointerInner.width() / 2));
let pointerLeftOffset = (e.pageX - $elem.offset().left - ($pointerInner.width() / 2));
if (pointerLeftOffset < 0) pointerLeftOffset = 0;
var pointerLeftOffsetPercent = (pointerLeftOffset / $elem.width()) * 100;
let pointerLeftOffsetPercent = (pointerLeftOffset / $elem.width()) * 100;
$pointerInner.css('left', pointerLeftOffsetPercent + '%');
isSelection = true;
......@@ -57,10 +75,12 @@ window.setupPageShow = module.exports = function (pageId) {
// Go to, and highlight if necessary, the specified text.
function goToText(text) {
var idElem = $('.page-content #' + text).first();
if (idElem.length !== 0) {
idElem.smoothScrollTo();
idElem.css('background-color', 'rgba(244, 249, 54, 0.25)');
let idElem = document.getElementById(text);
$('.page-content [data-highlighted]').attr('data-highlighted', '').css('background-color', '');
if (idElem !== null) {
let $idElem = $(idElem);
let color = $('#custom-styles').attr('data-color-light');
$idElem.css('background-color', color).attr('data-highlighted', 'true').smoothScrollTo();
} else {
$('.page-content').find(':contains("' + text + '")').smoothScrollTo();
}
......@@ -68,19 +88,24 @@ window.setupPageShow = module.exports = function (pageId) {
// Check the hash on load
if (window.location.hash) {
var text = window.location.hash.replace(/\%20/g, ' ').substr(1);
let text = window.location.hash.replace(/\%20/g, ' ').substr(1);
goToText(text);
}
// Sidebar page nav click event
$('.sidebar-page-nav').on('click', 'a', event => {
goToText(event.target.getAttribute('href').substr(1));
});
// Make the book-tree sidebar stick in view on scroll
var $window = $(window);
var $bookTree = $(".book-tree");
var $bookTreeParent = $bookTree.parent();
let $window = $(window);
let $bookTree = $(".book-tree");
let $bookTreeParent = $bookTree.parent();
// Check the page is scrollable and the content is taller than the tree
var pageScrollable = ($(document).height() > $window.height()) && ($bookTree.height() < $('.page-content').height());
let pageScrollable = ($(document).height() > $window.height()) && ($bookTree.height() < $('.page-content').height());
// Get current tree's width and header height
var headerHeight = $("#header").height() + $(".toolbar").height();
var isFixed = $window.scrollTop() > headerHeight;
let headerHeight = $("#header").height() + $(".toolbar").height();
let isFixed = $window.scrollTop() > headerHeight;
// Function to fix the tree as a sidebar
function stickTree() {
$bookTree.width($bookTreeParent.width() + 15);
......@@ -95,7 +120,7 @@ window.setupPageShow = module.exports = function (pageId) {
}
// Checks if the tree stickiness state should change
function checkTreeStickiness(skipCheck) {
var shouldBeFixed = $window.scrollTop() > headerHeight;
let shouldBeFixed = $window.scrollTop() > headerHeight;
if (shouldBeFixed && (!isFixed || skipCheck)) {
stickTree();
} else if (!shouldBeFixed && (isFixed || skipCheck)) {
......
/**
* Translation Manager
* Handles the JavaScript side of translating strings
* in a way which fits with Laravel.
*/
class Translator {
/**
* Create an instance, Passing in the required translations
* @param translations
*/
constructor(translations) {
this.store = translations;
}
/**
* Get a translation, Same format as laravel's 'trans' helper
* @param key
* @param replacements
* @returns {*}
*/
get(key, replacements) {
let splitKey = key.split('.');
let value = splitKey.reduce((a, b) => {
return a != undefined ? a[b] : a;
}, this.store);
if (value === undefined) {
console.log(`Translation with key "${key}" does not exist`);
value = key;
}
if (replacements === undefined) return value;
let replaceMatches = value.match(/:([\S]+)/g);
if (replaceMatches === null) return value;
replaceMatches.forEach(match => {
let key = match.substring(1);
if (typeof replacements[key] === 'undefined') return;
value = value.replace(match, replacements[key]);
});
return value;
}
}
export default Translator
......@@ -136,9 +136,6 @@
background-color: #EEE;
padding: $-s;
display: block;
> * {
display: inline-block;
}
&:before {
font-family: 'Material-Design-Iconic-Font';
padding-right: $-s;
......
......@@ -108,5 +108,4 @@ $button-border-radius: 2px;
cursor: default;
box-shadow: none;
}
}
}
\ No newline at end of file
......
......@@ -70,9 +70,6 @@ body.flexbox-support #entity-selector-wrap .popup-body .form-group {
#entity-selector-wrap .popup-body .form-group {
margin: 0;
}
//body.ie #entity-selector-wrap .popup-body .form-group {
// min-height: 60vh;
//}
.image-manager-body {
min-height: 70vh;
......@@ -465,4 +462,8 @@ body.flexbox-support #entity-selector-wrap .popup-body .form-group {
border-bottom-width: 3px;
}
}
}
.image-picker .none {
display: none;
}
\ No newline at end of file
......
......@@ -33,7 +33,7 @@
position: relative;
z-index: 5;
textarea {
font-family: 'Roboto Mono';
font-family: 'Roboto Mono', monospace;
font-style: normal;
font-weight: 400;
padding: $-xs $-m;
......@@ -55,6 +55,7 @@
display: flex;
flex-direction: column;
border: 1px solid #DDD;
width: 50%;
}
.markdown-display {
padding: 0 $-m 0;
......@@ -68,7 +69,7 @@
.editor-toolbar {
width: 100%;
padding: $-xs $-m;
font-family: 'Roboto Mono';
font-family: 'Roboto Mono', monospace;
font-size: 11px;
line-height: 1.6;
border-bottom: 1px solid #DDD;
......@@ -267,9 +268,4 @@ input.outline {
.image-picker img {
background-color: #BBB;
}
div[toggle-switch] {
height: 18px;
width: 150px;
}
\ No newline at end of file
......
......@@ -322,6 +322,9 @@ ul.pagination {
font-size: 0.75em;
margin-top: $-xs;
}
.text-muted p.text-muted {
margin-top: 0;
}
.page.draft .text-page {
color: $color-page-draft;
}
......
......@@ -138,6 +138,10 @@
font-size: 18px;
padding-top: 4px;
}
span.icon {
cursor: pointer;
user-select: none;
}
.button {
line-height: 1;
margin: 0 0 0 -4px;
......
......@@ -35,6 +35,12 @@ table.table {
tr:hover {
background-color: #EEE;
}
.text-right {
text-align: right;
}
.text-center {
text-align: center;
}
}
table.no-style {
......
......@@ -109,6 +109,9 @@ em, i, .italic {
small, p.small, span.small, .text-small {
font-size: 0.8em;
color: lighten($text-dark, 20%);
small, p.small, span.small, .text-small {
font-size: 1em;
}
}
sup, .superscript {
......@@ -172,6 +175,7 @@ pre code {
background-color: transparent;
border: 0;
font-size: 1em;
display: block;
}
/*
* Text colors
......
//@import "reset";
@import "reset";
@import "variables";
@import "mixins";
@import "html";
......
......@@ -16,7 +16,7 @@ return [
'app_name_desc' => 'Dieser Name wird im Header und E-Mails angezeigt.',
'app_name_header' => 'Anwendungsname im Header anzeigen?',
'app_public_viewing' => '&Ouml;ffentliche Ansicht erlauben?',
'app_secure_images' => 'Erh&oml;hte Sicherheit f&uuml;r Bilduploads aktivieren?',
'app_secure_images' => 'Erh&ouml;hte Sicherheit f&uuml;r Bilduploads aktivieren?',
'app_secure_images_desc' => 'Aus Leistungsgr&uuml;nden sind alle Bilder &ouml;ffentlich sichtbar. Diese Option f&uuml;gt zuf&auml;llige, schwer zu eratene, Zeichenketten vor die Bild-URLs hinzu. Stellen sie sicher, dass Verzeichnindexes deaktiviert sind, um einen einfachen Zugrif zu verhindern.',
'app_editor' => 'Seiteneditor',
'app_editor_desc' => 'W&auml;hlen sie den Editor aus, der von allen Benutzern genutzt werden soll, um Seiten zu editieren.',
......
......@@ -14,7 +14,49 @@ return [
'throttle' => 'Too many login attempts. Please try again in :seconds seconds.',
/**
* Email Confirmation Text
* Login & Register
*/
'sign_up' => 'Sign up',
'log_in' => 'Log in',
'logout' => 'Logout',
'name' => 'Name',
'username' => 'Username',
'email' => 'Email',
'password' => 'Password',
'password_confirm' => 'Confirm Password',
'password_hint' => 'Must be over 5 characters',
'forgot_password' => 'Forgot Password?',
'remember_me' => 'Remember Me',
'ldap_email_hint' => 'Please enter an email to use for this account.',
'create_account' => 'Create Account',
'social_login' => 'Social Login',
'social_registration' => 'Social Registration',
'social_registration_text' => 'Register and sign in using another service.',
'register_thanks' => 'Thanks for registering!',
'register_confirm' => 'Please check your email and click the confirmation button to access :appName.',
'registrations_disabled' => 'Registrations are currently disabled',
'registration_email_domain_invalid' => 'That email domain does not have access to this application',
'register_success' => 'Thanks for signing up! You are now registered and signed in.',
/**
* Password Reset
*/
'reset_password' => 'Reset Password',
'reset_password_send_instructions' => 'Enter your email below and you will be sent an email with a password reset link.',
'reset_password_send_button' => 'Send Reset Link',
'reset_password_sent_success' => 'A password reset link has been sent to :email.',
'reset_password_success' => 'Your password has been successfully reset.',
'email_reset_subject' => 'Reset your :appName password',
'email_reset_text' => 'You are receiving this email because we received a password reset request for your account.',
'email_reset_not_requested' => 'If you did not request a password reset, no further action is required.',
/**
* Email Confirmation
*/
'email_confirm_subject' => 'Confirm your email on :appName',
'email_confirm_greeting' => 'Thanks for joining :appName!',
......@@ -23,4 +65,10 @@ return [
'email_confirm_send_error' => 'Email confirmation required but the system could not send the email. Contact the admin to ensure email is set up correctly.',
'email_confirm_success' => 'Your email has been confirmed!',
'email_confirm_resent' => 'Confirmation email resent, Please check your inbox.',
'email_not_confirmed' => 'Email Address Not Confirmed',
'email_not_confirmed_text' => 'Your email address has not yet been confirmed.',
'email_not_confirmed_click_link' => 'Please click the link in the email that was sent shortly after you registered.',
'email_not_confirmed_resend' => 'If you cannot find the email you can re-send the confirmation email by submitting the form below.',
'email_not_confirmed_resend_button' => 'Resend Confirmation Email',
];
\ No newline at end of file
......
<?php
return [
/**
* Buttons
*/
'cancel' => 'Cancel',
'confirm' => 'Confirm',
'back' => 'Back',
'save' => 'Save',
'continue' => 'Continue',
'select' => 'Select',
/**
* Form Labels
*/
'name' => 'Name',
'description' => 'Description',
'role' => 'Role',
/**
* Actions
*/
'actions' => 'Actions',
'view' => 'View',
'create' => 'Create',
'update' => 'Update',
'edit' => 'Edit',
'sort' => 'Sort',
'move' => 'Move',
'delete' => 'Delete',
'search' => 'Search',
'search_clear' => 'Clear Search',
'reset' => 'Reset',
'remove' => 'Remove',
/**
* Misc
*/
'deleted_user' => 'Deleted User',
'no_activity' => 'No activity to show',
'no_items' => 'No items available',
'back_to_top' => 'Back to top',
'toggle_details' => 'Toggle Details',
/**
* Header
*/
'view_profile' => 'View Profile',
'edit_profile' => 'Edit Profile',
/**
* Email Content
*/
'email_action_help' => 'If you’re having trouble clicking the ":actionText" button, copy and paste the URL below into your web browser:',
'email_rights' => 'All rights reserved',
];
\ No newline at end of file
<?php
return [
/**
* Image Manager
*/
'image_select' => 'Image Select',
'image_all' => 'All',
'image_all_title' => 'View all images',
'image_book_title' => 'View images uploaded to this book',
'image_page_title' => 'View images uploaded to this page',
'image_search_hint' => 'Search by image name',
'image_uploaded' => 'Uploaded :uploadedDate',
'image_load_more' => 'Load More',
'image_image_name' => 'Image Name',
'image_delete_confirm' => 'This image is used in the pages below, Click delete again to confirm you want to delete this image.',
'image_select_image' => 'Select Image',
'image_dropzone' => 'Drop images or click here to upload',
'images_deleted' => 'Images Deleted',
'image_preview' => 'Image Preview',
'image_upload_success' => 'Image uploaded successfully',
'image_update_success' => 'Image details successfully updated',
'image_delete_success' => 'Image successfully deleted'
];
\ No newline at end of file
......@@ -6,7 +6,65 @@ return [
* Error text strings.
*/
// Pages
// Permissions
'permission' => 'You do not have permission to access the requested page.',
'permissionJson' => 'You do not have permission to perform the requested action.'
'permissionJson' => 'You do not have permission to perform the requested action.',
// Auth
'error_user_exists_different_creds' => 'A user with the email :email already exists but with different credentials.',
'email_already_confirmed' => 'Email has already been confirmed, Try logging in.',
'email_confirmation_invalid' => 'This confirmation token is not valid or has already been used, Please try registering again.',
'email_confirmation_expired' => 'The confirmation token has expired, A new confirmation email has been sent.',
'ldap_fail_anonymous' => 'LDAP access failed using anonymous bind',
'ldap_fail_authed' => 'LDAP access failed using given dn & password details',
'ldap_extension_not_installed' => 'LDAP PHP extension not installed',
'ldap_cannot_connect' => 'Cannot connect to ldap server, Initial connection failed',
'social_no_action_defined' => 'No action defined',
'social_account_in_use' => 'This :socialAccount account is already in use, Try logging in via the :socialAccount option.',
'social_account_email_in_use' => 'The email :email is already in use. If you already have an account you can connect your :socialAccount account from your profile settings.',
'social_account_existing' => 'This :socialAccount is already attached to your profile.',
'social_account_already_used_existing' => 'This :socialAccount account is already used by another user.',
'social_account_not_used' => 'This :socialAccount account is not linked to any users. Please attach it in your profile settings. ',
'social_account_register_instructions' => 'If you do not yet have an account, You can register an account using the :socialAccount option.',
'social_driver_not_found' => 'Social driver not found',
'social_driver_not_configured' => 'Your :socialAccount social settings are not configured correctly.',
// System
'path_not_writable' => 'File path :filePath could not be uploaded to. Ensure it is writable to the server.',
'cannot_get_image_from_url' => 'Cannot get image from :url',
'cannot_create_thumbs' => 'The server cannot create thumbnails. Please check you have the GD PHP extension installed.',
'server_upload_limit' => 'The server does not allow uploads of this size. Please try a smaller file size.',
'image_upload_error' => 'An error occurred uploading the image',
// Attachments
'attachment_page_mismatch' => 'Page mismatch during attachment update',
// Pages
'page_draft_autosave_fail' => 'Failed to save draft. Ensure you have internet connection before saving this page',
// Entities
'entity_not_found' => 'Entity not found',
'book_not_found' => 'Book not found',
'page_not_found' => 'Page not found',
'chapter_not_found' => 'Chapter not found',
'selected_book_not_found' => 'The selected book was not found',
'selected_book_chapter_not_found' => 'The selected Book or Chapter was not found',
'guests_cannot_save_drafts' => 'Guests cannot save drafts',
// Users
'users_cannot_delete_only_admin' => 'You cannot delete the only admin',
'users_cannot_delete_guest' => 'You cannot delete the guest user',
// Roles
'role_cannot_be_edited' => 'This role cannot be edited',
'role_system_cannot_be_deleted' => 'This role is a system role and cannot be deleted',
'role_registration_default_cannot_delete' => 'This role cannot be deleted while set as the default registration role',
// Error pages
'404_page_not_found' => 'Page Not Found',
'sorry_page_not_found' => 'Sorry, The page you were looking for could not be found.',
'return_home' => 'Return to home',
'error_occurred' => 'An Error Occurred',
'app_down' => ':appName is down right now',
'back_soon' => 'It will be back up soon.',
];
\ No newline at end of file
......
<?php
return [
/**
* Settings text strings
* Contains all text strings used in the general settings sections of BookStack
* including users and roles.
*/
'settings' => 'Settings',
'settings_save' => 'Save Settings',
'settings_save_success' => 'Settings saved',
/**
* App settings
*/
'app_settings' => 'App Settings',
'app_name' => 'Application name',
'app_name_desc' => 'This name is shown in the header and any emails.',
......@@ -27,6 +32,10 @@ return [
'app_primary_color' => 'Application primary color',
'app_primary_color_desc' => 'This should be a hex value. <br>Leave empty to reset to the default color.',
/**
* Registration settings
*/
'reg_settings' => 'Registration Settings',
'reg_allow' => 'Allow registration?',
'reg_default_role' => 'Default user role after registration',
......@@ -36,4 +45,79 @@ return [
'reg_confirm_restrict_domain_desc' => 'Enter a comma separated list of email domains you would like to restrict registration to. Users will be sent an email to confirm their address before being allowed to interact with the application. <br> Note that users will be able to change their email addresses after successful registration.',
'reg_confirm_restrict_domain_placeholder' => 'No restriction set',
];
\ No newline at end of file
/**
* Role settings
*/
'roles' => 'Roles',
'role_user_roles' => 'User Roles',
'role_create' => 'Create New Role',
'role_create_success' => 'Role successfully created',
'role_delete' => 'Delete Role',
'role_delete_confirm' => 'This will delete the role with the name \':roleName\'.',
'role_delete_users_assigned' => 'This role has :userCount users assigned to it. If you would like to migrate the users from this role select a new role below.',
'role_delete_no_migration' => "Don't migrate users",
'role_delete_sure' => 'Are you sure you want to delete this role?',
'role_delete_success' => 'Role successfully deleted',
'role_edit' => 'Edit Role',
'role_details' => 'Role Details',
'role_name' => 'Role Name',
'role_desc' => 'Short Description of Role',
'role_system' => 'System Permissions',
'role_manage_users' => 'Manage users',
'role_manage_roles' => 'Manage roles & role permissions',
'role_manage_entity_permissions' => 'Manage all book, chapter & page permissions',
'role_manage_own_entity_permissions' => 'Manage permissions on own book, chapter & pages',
'role_manage_settings' => 'Manage app settings',
'role_asset' => 'Asset Permissions',
'role_asset_desc' => 'These permissions control default access to the assets within the system. Permissions on Books, Chapters and Pages will override these permissions.',
'role_all' => 'All',
'role_own' => 'Own',
'role_controlled_by_asset' => 'Controlled by the asset they are uploaded to',
'role_save' => 'Save Role',
'role_update_success' => 'Role successfully updated',
'role_users' => 'Users in this role',
'role_users_none' => 'No users are currently assigned to this role',
/**
* Users
*/
'users' => 'Users',
'user_profile' => 'User Profile',
'users_add_new' => 'Add New User',
'users_search' => 'Search Users',
'users_role' => 'User Roles',
'users_external_auth_id' => 'External Authentication ID',
'users_password_warning' => 'Only fill the below if you would like to change your password:',
'users_system_public' => 'This user represents any guest users that visit your instance. It cannot be used to log in but is assigned automatically.',
'users_delete' => 'Delete User',
'users_delete_named' => 'Delete user :userName',
'users_delete_warning' => 'This will fully delete this user with the name \':userName\' from the system.',
'users_delete_confirm' => 'Are you sure you want to delete this user?',
'users_delete_success' => 'Users successfully removed',
'users_edit' => 'Edit User',
'users_edit_profile' => 'Edit Profile',
'users_edit_success' => 'User successfully updated',
'users_avatar' => 'User Avatar',
'users_avatar_desc' => 'This image should be approx 256px square.',
'users_preferred_language' => 'Preferred Language',
'users_social_accounts' => 'Social Accounts',
'users_social_accounts_info' => 'Here you can connect your other accounts for quicker and easier login. Disconnecting an account here does not previously authorized access. Revoke access from your profile settings on the connected social account.',
'users_social_connect' => 'Connect Account',
'users_social_disconnect' => 'Disconnect Account',
'users_social_connected' => ':socialAccount account was successfully attached to your profile.',
'users_social_disconnected' => ':socialAccount account was successfully disconnected from your profile.',
// Since these labels are already localized this array does not need to be
// translated in the language-specific files.
// DELETE BELOW IF COPIED FROM EN
///////////////////////////////////
'language_select' => [
'en' => 'English',
'de' => 'Deutsch',
'fr' => 'Français',
'pt_BR' => 'Português do Brasil'
]
///////////////////////////////////
];
......
......@@ -87,8 +87,8 @@ return [
*/
'custom' => [
'attribute-name' => [
'rule-name' => 'custom-message',
'password-confirm' => [
'required_with' => 'Password confirmation required',
],
],
......
<?php
return [
/**
* Activity text strings.
* Is used for all the text within activity logs & notifications.
*/
// Pages
'page_create' => 'a créé la page',
'page_create_notification' => 'Page créée avec succès',
'page_update' => 'a modifié la page',
'page_update_notification' => 'Page modifiée avec succès',
'page_delete' => 'a supprimé la page',
'page_delete_notification' => 'Page supprimée avec succès',
'page_restore' => 'a restauré la page',
'page_restore_notification' => 'Page réstaurée avec succès',
'page_move' => 'a déplacé la page',
// Chapters
'chapter_create' => 'a créé le chapitre',
'chapter_create_notification' => 'Chapitre créé avec succès',
'chapter_update' => 'a modifié le chapitre',
'chapter_update_notification' => 'Chapitre modifié avec succès',
'chapter_delete' => 'a supprimé le chapitre',
'chapter_delete_notification' => 'Chapitre supprimé avec succès',
'chapter_move' => 'a déplacé le chapitre',
// Books
'book_create' => 'a créé le livre',
'book_create_notification' => 'Livre créé avec succès',
'book_update' => 'a modifié le livre',
'book_update_notification' => 'Livre modifié avec succès',
'book_delete' => 'a supprimé le livre',
'book_delete_notification' => 'Livre supprimé avec succès',
'book_sort' => 'a réordonné le livre',
'book_sort_notification' => 'Livre réordonné avec succès',
];
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used during authentication for various
| messages that we need to display to the user. You are free to modify
| these language lines according to your application's requirements.
|
*/
'failed' => 'Ces informations ne correspondent a aucun compte.',
'throttle' => "Trop d'essais, veuillez réessayer dans :seconds secondes.",
/**
* Login & Register
*/
'sign_up' => "S'inscrire",
'log_in' => 'Se connecter',
'logout' => 'Se déconnecter',
'name' => 'Nom',
'username' => "Nom d'utilisateur",
'email' => 'E-mail',
'password' => 'Mot de passe',
'password_confirm' => 'Confirmez le mot de passe',
'password_hint' => 'Doit faire plus de 5 caractères',
'forgot_password' => 'Mot de passe oublié?',
'remember_me' => 'Se souvenir de moi',
'ldap_email_hint' => "Merci d'entrer une adresse e-mail pour ce compte",
'create_account' => 'Créer un compte',
'social_login' => 'Social Login',
'social_registration' => 'Enregistrement Social',
'social_registration_text' => "S'inscrire et se connecter avec un réseau social",
'register_thanks' => 'Merci pour votre enregistrement',
'register_confirm' => 'Vérifiez vos e-mails et cliquer sur le lien de confirmation pour rejoindre :appName.',
'registrations_disabled' => "L'inscription est désactivée pour le moment",
'registration_email_domain_invalid' => 'Cette adresse e-mail ne peux pas adcéder à l\'application',
'register_success' => 'Merci pour votre inscription. Vous êtes maintenant inscrit(e) et connecté(e)',
/**
* Password Reset
*/
'reset_password' => 'Reset Password',
'reset_password_send_instructions' => 'Entrez votre adresse e-mail ci-dessous et un e-mail avec un lien de réinitialisation de mot de passe vous sera envoyé',
'reset_password_send_button' => 'Envoyer un lien de réinitialisation',
'reset_password_sent_success' => 'Un lien de réinitialisation a été envoyé à :email.',
'reset_password_success' => 'Votre mot de passe a été réinitialisé avec succès.',
'email_reset_subject' => 'Réinitialisez votre mot de passe pour :appName',
'email_reset_text' => 'Vous recevez cet e-mail parceque nous avons reçu une demande de réinitialisation pour votre compte',
'email_reset_not_requested' => 'Si vous n\'avez pas effectué cette demande, vous pouvez ignorer cet e-mail.',
/**
* Email Confirmation
*/
'email_confirm_subject' => 'Confirmez votre adresse e-mail pour :appName',
'email_confirm_greeting' => 'Merci d\'avoir rejoint :appName!',
'email_confirm_text' => 'Merci de confirmer en cliquant sur le lien ci-dessous:',
'email_confirm_action' => 'Confirmez votre adresse e-mail',
'email_confirm_send_error' => 'La confirmation par e-mail est requise mais le système n\'a pas pu envoyer l\'e-mail. Contactez l\'administrateur système.',
'email_confirm_success' => 'Votre adresse e-mail a été confirmée!',
'email_confirm_resent' => 'L\'e-mail de confirmation a été ré-envoyé. Vérifiez votre boîte de récéption.',
'email_not_confirmed' => 'Adresse e-mail non confirmée',
'email_not_confirmed_text' => 'Votre adresse e-mail n\'a pas été confirmée.',
'email_not_confirmed_click_link' => 'Merci de cliquer sur le lien dans l\'e-mail qui vous a été envoyé après l\'enregistrement.',
'email_not_confirmed_resend' => 'Si vous ne retrouvez plus l\'e-mail, vous pouvez renvoyer un e-mail de confirmation en utilisant le formulaire ci-dessous.',
'email_not_confirmed_resend_button' => 'Renvoyez l\'e-mail de confirmation',
];
<?php
return [
/**
* Buttons
*/
'cancel' => 'Annuler',
'confirm' => 'Confirmer',
'back' => 'Retour',
'save' => 'Enregistrer',
'continue' => 'Continuer',
'select' => 'Selectionner',
/**
* Form Labels
*/
'name' => 'Nom',
'description' => 'Description',
'role' => 'Rôle',
/**
* Actions
*/
'actions' => 'Actions',
'view' => 'Voir',
'create' => 'Créer',
'update' => 'Modifier',
'edit' => 'Editer',
'sort' => 'Trier',
'move' => 'Déplacer',
'delete' => 'Supprimer',
'search' => 'Chercher',
'search_clear' => 'Réinitialiser la recherche',
'reset' => 'Réinitialiser',
'remove' => 'Enlever',
/**
* Misc
*/
'deleted_user' => 'Utilisateur supprimé',
'no_activity' => 'Aucune activité',
'no_items' => 'Aucun élément',
'back_to_top' => 'Retour en haut',
'toggle_details' => 'Afficher les détails',
/**
* Header
*/
'view_profile' => 'Voir le profil',
'edit_profile' => 'Modifier le profil',
/**
* Email Content
*/
'email_action_help' => 'Si vous rencontrez des problèmes pour cliquer le bouton ":actionText", copiez et collez l\'adresse ci-dessous dans votre navigateur:',
'email_rights' => 'Tous droits réservés',
];
<?php
return [
/**
* Image Manager
*/
'image_select' => 'Selectionner une image',
'image_all' => 'Toutes',
'image_all_title' => 'Voir toutes les images',
'image_book_title' => 'Voir les images ajoutées à ce livre',
'image_page_title' => 'Voir les images ajoutées à cette page',
'image_search_hint' => 'Rechercher par nom d\'image',
'image_uploaded' => 'Ajoutée le :uploadedDate',
'image_load_more' => 'Charger plus',
'image_image_name' => 'Nom de l\'image',
'image_delete_confirm' => 'Cette image est utilisée dans les pages ci-dessous. Confirmez que vous souhaitez bien supprimer cette image.',
'image_select_image' => 'Selectionner l\'image',
'image_dropzone' => 'Glissez les images ici ou cliquez pour les ajouter',
'images_deleted' => 'Images supprimées',
'image_preview' => 'Prévisualiser l\'image',
'image_upload_success' => 'Image ajoutée avec succès',
'image_update_success' => 'Détails de l\'image mis à jour',
'image_delete_success' => 'Image supprimée avec succès'
];
<?php
return [
/**
* Error text strings.
*/
// Permissions
'permission' => 'Vous n\'avez pas les droits pour accéder à cette page.',
'permissionJson' => 'Vous n\'avez pas les droits pour exécuter cette action.',
// Auth
'error_user_exists_different_creds' => 'Un utilisateur avec l\'adresse :email existe déjà.',
'email_already_confirmed' => 'Cet e-mail a déjà été validé, vous pouvez vous connecter.',
'email_confirmation_invalid' => 'Cette confirmation est invalide. Veuillez essayer de vous inscrire à nouveau.',
'email_confirmation_expired' => 'Le jeton de confirmation est perimé. Un nouvel e-mail vous a été envoyé.',
'ldap_fail_anonymous' => 'L\'accès LDAP anonyme n\'a pas abouti',
'ldap_fail_authed' => 'L\'accès LDAP n\'a pas abouti avec cet utilisateur et ce mot de passe',
'ldap_extension_not_installed' => 'L\'extention LDAP PHP n\'est pas installée',
'ldap_cannot_connect' => 'Cannot connect to ldap server, Initial connection failed',
'social_no_action_defined' => 'No action defined',
'social_account_in_use' => 'Cet compte :socialAccount est déjà utilisé. Essayez de vous connecter via :socialAccount.',
'social_account_email_in_use' => 'L\'email :email Est déjà utilisé. Si vous avez déjà un compte :socialAccount, vous pouvez le joindre à votre profil existant.',
'social_account_existing' => 'Ce compte :socialAccount est déjà rattaché à votre profil.',
'social_account_already_used_existing' => 'Ce compte :socialAccount est déjà utilisé par un autre utilisateur.',
'social_account_not_used' => 'Ce compte :socialAccount n\'est lié à aucun utilisateur. ',
'social_account_register_instructions' => 'Si vous n\'avez pas encore de compte, vous pouvez le lier avec l\'option :socialAccount.',
'social_driver_not_found' => 'Social driver not found',
'social_driver_not_configured' => 'Your :socialAccount social settings are not configured correctly.',
// System
'path_not_writable' => 'File path :filePath could not be uploaded to. Ensure it is writable to the server.',
'cannot_get_image_from_url' => 'Impossible de récupérer l\'image depuis :url',
'cannot_create_thumbs' => 'Le serveur ne peux pas créer de miniatures, vérifier que l\extensions GD PHP est installée.',
'server_upload_limit' => 'La taille du fichier est trop grande.',
'image_upload_error' => 'Une erreur est survenue pendant l\'envoi de l\'image',
// Attachments
'attachment_page_mismatch' => 'Page mismatch during attachment update',
// Pages
'page_draft_autosave_fail' => 'Le brouillon n\'a pas pu être sauvé. Vérifiez votre connexion internet',
// Entities
'entity_not_found' => 'Entité non trouvée',
'book_not_found' => 'Livre non trouvé',
'page_not_found' => 'Page non trouvée',
'chapter_not_found' => 'Chapitre non trouvé',
'selected_book_not_found' => 'Ce livre n\'a pas été trouvé',
'selected_book_chapter_not_found' => 'Ce livre ou chapitre n\'a pas été trouvé',
'guests_cannot_save_drafts' => 'Les invités ne peuvent pas sauver de brouillons',
// Users
'users_cannot_delete_only_admin' => 'Vous ne pouvez pas supprimer le dernier admin',
'users_cannot_delete_guest' => 'Vous ne pouvez pas supprimer l\'utilisateur invité',
// Roles
'role_cannot_be_edited' => 'Ce rôle ne peut pas être modifié',
'role_system_cannot_be_deleted' => 'Ceci est un rôle du système et on ne peut pas le supprimer',
'role_registration_default_cannot_delete' => 'Ce rôle ne peut pas être supprimé tant qu\'il est le rôle par défaut',
// Error pages
'404_page_not_found' => 'Page non trouvée',
'sorry_page_not_found' => 'Désolé, cette page n\'a pas pu être trouvée.',
'return_home' => 'Retour à l\'accueil',
'error_occurred' => 'Une erreur est survenue',
'app_down' => ':appName n\'est pas en service pour le moment',
'back_soon' => 'Nous serons bientôt de retour.',
];
<?php
return [
/*
|--------------------------------------------------------------------------
| Pagination Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used by the paginator library to build
| the simple pagination links. You are free to change them to anything
| you want to customize your views to better match your application.
|
*/
'previous' => '&laquo; Précédent',
'next' => 'Suivant &raquo;',
];
<?php
return [
/*
|--------------------------------------------------------------------------
| Password Reminder Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are the default lines which match reasons
| that are given by the password broker for a password update attempt
| has failed, such as for an invalid token or invalid new password.
|
*/
'password' => 'Les mots de passe doivent faire au moins 6 caractères et correspondre à la confirmation.',
'user' => "Nous n'avons pas trouvé d'utilisateur avec cette adresse.",
'token' => 'Le jeton de réinitialisation est invalide.',
'sent' => 'Nous vous avons envoyé un lien de réinitialisation de mot de passe!',
'reset' => 'Votre mot de passe a été réinitialisé!',
];
<?php
return [
/**
* Settings text strings
* Contains all text strings used in the general settings sections of BookStack
* including users and roles.
*/
'settings' => 'Préférences',
'settings_save' => 'Enregistrer les préférences',
'settings_save_success' => 'Préférences enregistrées',
/**
* App settings
*/
'app_settings' => 'Préférences de l\'application',
'app_name' => 'Nom de l\'application',
'app_name_desc' => 'Ce nom est affiché dans l\'en-tête et les e-mails.',
'app_name_header' => 'Afficher le nom dans l\'en-tête?',
'app_public_viewing' => 'Accepter le visionnage public des pages?',
'app_secure_images' => 'Activer l\'ajout d\'image sécurisé?',
'app_secure_images_desc' => 'Pour des questions de performances, toutes les images sont publiques. Cette option ajoute une chaîne aléatoire difficile à deviner dans les URLs des images.',
'app_editor' => 'Editeur des pages',
'app_editor_desc' => 'Sélectionnez l\'éditeur qui sera utilisé pour modifier les pages.',
'app_custom_html' => 'HTML personnalisé dans l\'en-tête',
'app_custom_html_desc' => 'Le contenu inséré ici sera jouté en bas de la balise <head> de toutes les pages. Vous pouvez l\'utiliser pour ajouter du CSS personnalisé ou un tracker analytique.',
'app_logo' => 'Logo de l\'Application',
'app_logo_desc' => 'Cette image doit faire 43px de hauteur. <br>Les images plus larges seront réduites.',
'app_primary_color' => 'Couleur principale de l\'application',
'app_primary_color_desc' => 'This should be a hex value. <br>Leave empty to reset to the default color.',
/**
* Registration settings
*/
'reg_settings' => 'Préférence pour l\'inscription',
'reg_allow' => 'Accepter l\'inscription?',
'reg_default_role' => 'Rôle par défaut lors de l\'inscription',
'reg_confirm_email' => 'Obliger la confirmation par e-mail?',
'reg_confirm_email_desc' => 'Si la restriction de domaine est activée, la confirmation sera automatiquement obligatoire et cette valeur sera ignorée.',
'reg_confirm_restrict_domain' => 'Restreindre l\'inscription à un domaine',
'reg_confirm_restrict_domain_desc' => 'Entrez une liste de domaines acceptés lors de l\'inscription, séparés par une virgule. Les utilisateur recevront un e-mail de confirmation à cette adresse. <br> Les utilisateurs pourront changer leur adresse après inscription s\'ils le souhaitent.',
'reg_confirm_restrict_domain_placeholder' => 'Aucune restriction en place',
/**
* Role settings
*/
'roles' => 'Rôles',
'role_user_roles' => 'Rôles des utilisateurs',
'role_create' => 'Créer un nouveau rôle',
'role_create_success' => 'Rôle créé avec succès',
'role_delete' => 'Supprimer le rôle',
'role_delete_confirm' => 'Ceci va supprimer le rôle \':roleName\'.',
'role_delete_users_assigned' => 'Ce rôle a :userCount utilisateurs assignés. Vous pouvez choisir un rôle de remplacement pour ces utilisateurs.',
'role_delete_no_migration' => "Ne pas assigner de nouveau rôle",
'role_delete_sure' => 'Êtes vous sûr(e) de vouloir supprimer ce rôle?',
'role_delete_success' => 'Le rôle a été supprimé avec succès',
'role_edit' => 'Modifier le rôle',
'role_details' => 'Détails du rôle',
'role_name' => 'Nom du Rôle',
'role_desc' => 'Courte description du rôle',
'role_system' => 'Permissions système',
'role_manage_users' => 'Gérer les utilisateurs',
'role_manage_roles' => 'Gérer les rôles et permissions',
'role_manage_entity_permissions' => 'Gérer les permissions sur les livres, chapitres et pages',
'role_manage_own_entity_permissions' => 'Gérer les permissions de ses propres livres chapitres et pages',
'role_manage_settings' => 'Gérer les préférences de l\'application',
'role_asset' => 'Asset Permissions',
'role_asset_desc' => 'These permissions control default access to the assets within the system. Permissions on Books, Chapters and Pages will override these permissions.',
'role_all' => 'Tous',
'role_own' => 'Propres',
'role_controlled_by_asset' => 'Controlled by the asset they are uploaded to',
'role_save' => 'Enregistrer le rôle',
'role_update_success' => 'Rôle mis à jour avec succès',
'role_users' => 'Utilisateurs ayant ce rôle',
'role_users_none' => 'Aucun utilisateur avec ce rôle actuellement',
/**
* Users
*/
'users' => 'Utilisateurs',
'user_profile' => 'Profil d\'utilisateur',
'users_add_new' => 'Ajouter un nouvel utilisateur',
'users_search' => 'Chercher les utilisateurs',
'users_role' => 'Rôles des utilisateurs',
'users_external_auth_id' => 'Identifiant d\'authentification externe',
'users_password_warning' => 'Remplissez ce fomulaire uniquement si vous souhaitez changer de mot de passe:',
'users_system_public' => 'Cet utilisateur représente les invités visitant votre instance. Il est assigné automatiquement aux invités.',
'users_delete' => 'Supprimer un utilisateur',
'users_delete_named' => 'Supprimer l\'utilisateur :userName',
'users_delete_warning' => 'Ceci va supprimer \':userName\' du système.',
'users_delete_confirm' => 'Êtes-vous sûr(e) de vouloir supprimer cet utilisateur?',
'users_delete_success' => 'Utilisateurs supprimés avec succès',
'users_edit' => 'Modifier l\'utilisateur',
'users_edit_profile' => 'Modifier le profil',
'users_edit_success' => 'Utilisateur mis à jour avec succès',
'users_avatar' => 'Avatar de l\'utilisateur',
'users_avatar_desc' => 'Cette image doit être un carré d\'environ 256px.',
'users_preferred_language' => 'Langue préférée',
'users_social_accounts' => 'Comptes sociaux',
'users_social_accounts_info' => 'Vous pouvez connecter des réseaux sociaux à votre compte pour vous connecter plus rapidement. Déconnecter un compte n\'enlèvera pas les accès autorisés précédemment sur votre compte de réseau social.',
'users_social_connect' => 'Connecter le compte',
'users_social_disconnect' => 'Déconnecter le compte',
'users_social_connected' => 'Votre compte :socialAccount a élté ajouté avec succès.',
'users_social_disconnected' => 'Votre compte :socialAccount a été déconnecté avec succès',
];
<?php
return [
/*
|--------------------------------------------------------------------------
| Validation Language Lines
|--------------------------------------------------------------------------
|
| The following language lines contain the default error messages used by
| the validator class. Some of these rules have multiple versions such
| as the size rules. Feel free to tweak each of these messages here.
|
*/
'accepted' => ':attribute doit être accepté.',
'active_url' => ':attribute n\'est pas une URL valide.',
'after' => ':attribute doit être supérieur à :date.',
'alpha' => ':attribute ne doit contenir que des lettres.',
'alpha_dash' => ':attribute doit contenir uniquement des lettres, chiffres et traits d\'union.',
'alpha_num' => ':attribute doit contenir uniquement des chiffres et des lettres.',
'array' => ':attribute doit être un tableau.',
'before' => ':attribute doit être inférieur à :date.',
'between' => [
'numeric' => ':attribute doit être compris entre :min et :max.',
'file' => ':attribute doit être compris entre :min et :max kilobytes.',
'string' => ':attribute doit être compris entre :min et :max caractères.',
'array' => ':attribute doit être compris entre :min et :max éléments.',
],
'boolean' => ':attribute doit être vrai ou faux.',
'confirmed' => ':attribute la confirmation n\'est pas valide.',
'date' => ':attribute n\'est pas une date valide.',
'date_format' => ':attribute ne correspond pas au format :format.',
'different' => ':attribute et :other doivent être différents l\'un de l\'autre.',
'digits' => ':attribute doit être de longueur :digits.',
'digits_between' => ':attribute doit avoir une longueur entre :min et :max.',
'email' => ':attribute doit être une adresse e-mail valide.',
'filled' => ':attribute est un champ requis.',
'exists' => 'L\'attribut :attribute est invalide.',
'image' => ':attribute doit être une image.',
'in' => 'L\'attribut :attribute est invalide.',
'integer' => ':attribute doit être un chiffre entier.',
'ip' => ':attribute doit être une adresse IP valide.',
'max' => [
'numeric' => ':attribute ne doit pas excéder :max.',
'file' => ':attribute ne doit pas excéder :max kilobytes.',
'string' => ':attribute ne doit pas excéder :max caractères.',
'array' => ':attribute ne doit pas contenir plus de :max éléments.',
],
'mimes' => ':attribute doit être un fichier de type :values.',
'min' => [
'numeric' => ':attribute doit être au moins :min.',
'file' => ':attribute doit faire au moins :min kilobytes.',
'string' => ':attribute doit contenir au moins :min caractères.',
'array' => ':attribute doit contenir au moins :min éléments.',
],
'not_in' => 'L\'attribut sélectionné :attribute est invalide.',
'numeric' => ':attribute doit être un nombre.',
'regex' => ':attribute a un format invalide.',
'required' => ':attribute est un champ requis.',
'required_if' => ':attribute est requis si :other est :value.',
'required_with' => ':attribute est requis si :values est présent.',
'required_with_all' => ':attribute est requis si :values est présent.',
'required_without' => ':attribute est requis si:values n\'est pas présent.',
'required_without_all' => ':attribute est requis si aucun des valeurs :values n\'est présente.',
'same' => ':attribute et :other doivent être identiques.',
'size' => [
'numeric' => ':attribute doit avoir la taille :size.',
'file' => ':attribute doit peser :size kilobytes.',
'string' => ':attribute doit contenir :size caractères.',
'array' => ':attribute doit contenir :size éléments.',
],
'string' => ':attribute doit être une chaîne de caractères.',
'timezone' => ':attribute doit être une zone valide.',
'unique' => ':attribute est déjà utilisé.',
'url' => ':attribute a un format invalide.',
/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/
'custom' => [
'password-confirm' => [
'required_with' => 'La confirmation du mot de passe est requise',
],
],
/*
|--------------------------------------------------------------------------
| Custom Validation Attributes
|--------------------------------------------------------------------------
|
| The following language lines are used to swap attribute place-holders
| with something more reader friendly such as E-Mail Address instead
| of "email". This simply helps us make messages a little cleaner.
|
*/
'attributes' => [],
];
<?php
return [
/**
* Activity text strings.
* Is used for all the text within activity logs & notifications.
*/
// Pages
'page_create' => 'página criada',
'page_create_notification' => 'Página criada com sucesso',
'page_update' => 'página atualizada',
'page_update_notification' => 'Página atualizada com sucesso',
'page_delete' => 'página excluída',
'page_delete_notification' => 'Página excluída com sucesso',
'page_restore' => 'página restaurada',
'page_restore_notification' => 'Página restaurada com sucesso',
'page_move' => 'página movida',
// Chapters
'chapter_create' => 'capítulo criado',
'chapter_create_notification' => 'Capítulo criado com sucesso',
'chapter_update' => 'capítulo atualizado',
'chapter_update_notification' => 'capítulo atualizado com sucesso',
'chapter_delete' => 'capítulo excluído',
'chapter_delete_notification' => 'Capítulo excluído com sucesso',
'chapter_move' => 'capitulo movido',
// Books
'book_create' => 'livro criado',
'book_create_notification' => 'Livro criado com sucesso',
'book_update' => 'livro atualizado',
'book_update_notification' => 'Livro atualizado com sucesso',
'book_delete' => 'livro excluído',
'book_delete_notification' => 'Livro excluído com sucesso',
'book_sort' => 'livro classificado',
'book_sort_notification' => 'Livro reclassificado com sucesso',
];
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used during authentication for various
| messages that we need to display to the user. You are free to modify
| these language lines according to your application's requirements.
|
*/
'failed' => 'As credenciais fornecidas não puderam ser validadas em nossos registros..',
'throttle' => 'Muitas tentativas de login. Por favor, tente novamente em :seconds segundos.',
/**
* Login & Register
*/
'sign_up' => 'Registrar-se',
'log_in' => 'Entrar',
'logout' => 'Sair',
'name' => 'Nome',
'username' => 'Nome de Usuário',
'email' => 'E-mail',
'password' => 'Senha',
'password_confirm' => 'Confirmar Senha',
'password_hint' => 'Senha deverá ser maior que 5 caracteres',
'forgot_password' => 'Esqueceu a senha?',
'remember_me' => 'Lembrar de mim',
'ldap_email_hint' => 'Por favor, digite um e-mail para essa conta.',
'create_account' => 'Criar conta',
'social_login' => 'Login social',
'social_registration' => 'Registro social',
'social_registration_text' => 'Registre e entre usando outro serviço.',
'register_thanks' => 'Obrigado por efetuar o registro!',
'register_confirm' => 'Por favor, verifique seu e-mail e clique no botão de confirmação para acessar :appName.',
'registrations_disabled' => 'Registros estão temporariamente desabilitados',
'registration_email_domain_invalid' => 'O domínio de e-mail usado não tem acesso permitido a essa aplicação',
'register_success' => 'Obrigado por se registrar! Você agora encontra-se registrado e logado..',
/**
* Password Reset
*/
'reset_password' => 'Resetar senha',
'reset_password_send_instructions' => 'Digite seu e-mail abaixo e o sistema enviará uma mensagem com o link de reset de senha.',
'reset_password_send_button' => 'Enviar o link de reset de senha',
'reset_password_sent_success' => 'Um link de reset de senha foi enviado para :email.',
'reset_password_success' => 'Sua senha foi resetada com sucesso.',
'email_reset_subject' => 'Resetar a senha de :appName',
'email_reset_text' => 'Você recebeu esse e-mail pois recebemos uma solicitação de reset de senha para sua conta.',
'email_reset_not_requested' => 'Caso não tenha sido você a solicitar o reset de senha, ignore esse e-mail.',
/**
* Email Confirmation
*/
'email_confirm_subject' => 'Confirme seu e-mail para :appName',
'email_confirm_greeting' => 'Obrigado por se registrar em :appName!',
'email_confirm_text' => 'Por favor, confirme seu endereço de e-mail clicando no botão abaixo:',
'email_confirm_action' => 'Confirmar E-mail',
'email_confirm_send_error' => 'E-mail de confirmação é requerido, mas o sistema não pôde enviar a mensagem. Por favor, entre em contato com o admin para se certificar que o serviço de envio de e-mails está corretamente configurado.',
'email_confirm_success' => 'Seu e-mail foi confirmado!',
'email_confirm_resent' => 'E-mail de confirmação reenviado. Por favor, cheque sua caixa postal.',
'email_not_confirmed' => 'Endereço de e-mail não foi confirmado',
'email_not_confirmed_text' => 'Seu endereço de e-mail ainda não foi confirmado.',
'email_not_confirmed_click_link' => 'Por favor, clique no link no e-mail que foi enviado após o registro.',
'email_not_confirmed_resend' => 'Caso não encontre o e-mail você poderá reenviar a confirmação usando o formulário abaixo.',
'email_not_confirmed_resend_button' => 'Reenviar o e-mail de confirmação',
];
\ No newline at end of file
<?php
return [
/**
* Buttons
*/
'cancel' => 'Cancelar',
'confirm' => 'Confirmar',
'back' => 'Voltar',
'save' => 'Salvar',
'continue' => 'Continuar',
'select' => 'Selecionar',
/**
* Form Labels
*/
'name' => 'Nome',
'description' => 'Descrição',
'role' => 'Regra',
/**
* Actions
*/
'actions' => 'Ações',
'view' => 'Visualizar',
'create' => 'Criar',
'update' => 'Atualizar',
'edit' => 'Editar',
'sort' => 'Ordenar',
'move' => 'Mover',
'delete' => 'Excluir',
'search' => 'Pesquisar',
'search_clear' => 'Limpar Pesquisa',
'reset' => 'Resetar',
'remove' => 'Remover',
/**
* Misc
*/
'deleted_user' => 'Usuário excluído',
'no_activity' => 'Nenhuma atividade a mostrar',
'no_items' => 'Nenhum item disponível',
'back_to_top' => 'Voltar ao topo',
'toggle_details' => 'Alternar Detalhes',
/**
* Header
*/
'view_profile' => 'Visualizar Perfil',
'edit_profile' => 'Editar Perfil',
/**
* Email Content
*/
'email_action_help' => 'Se você estiver tendo problemas ao clicar o botão ":actionText", copie e cole a URL abaixo no seu navegador:',
'email_rights' => 'Todos os direitos reservados',
];
\ No newline at end of file
<?php
return [
/**
* Image Manager
*/
'image_select' => 'Selecionar imagem',
'image_all' => 'Todos',
'image_all_title' => 'Visualizar todas as imagens',
'image_book_title' => 'Visualizar imagens relacionadas a esse livro',
'image_page_title' => 'visualizar imagens relacionadas a essa página',
'image_search_hint' => 'Pesquisar imagem por nome',
'image_uploaded' => 'Carregado :uploadedDate',
'image_load_more' => 'Carregar Mais',
'image_image_name' => 'Nome da Imagem',
'image_delete_confirm' => 'Essa imagem é usada nas páginas abaixo. Clique em Excluir novamente para confirmar que você deseja mesmo eliminar a imagem.',
'image_select_image' => 'Selecionar Imagem',
'image_dropzone' => 'Arraste imagens ou clique aqui para fazer upload',
'images_deleted' => 'Imagens excluídas',
'image_preview' => 'Virtualização de Imagem',
'image_upload_success' => 'Upload de imagem efetuado com sucesso',
'image_update_success' => 'Upload de detalhes da imagem efetuado com sucesso',
'image_delete_success' => 'Imagem excluída com sucesso'
];
\ No newline at end of file
<?php
return [
/**
* Error text strings.
*/
// Permissions
'permission' => 'Você não tem permissões para acessar a página requerida.',
'permissionJson' => 'Você não tem permissão para realizar a ação requerida.',
// Auth
'error_user_exists_different_creds' => 'Um usuário com o e-mail :email já existe mas com credenciais diferentes.',
'email_already_confirmed' => 'E-mail já foi confirmado. Tente efetuar o login.',
'email_confirmation_invalid' => 'Esse token de confirmação não é válido ou já foi utilizado. Por favor, tente efetuar o registro novamente.',
'email_confirmation_expired' => 'O token de confirmação já expirou. Um novo e-mail foi enviado.',
'ldap_fail_anonymous' => 'O acesso LDAP falhou ao tentar usar o anonymous bind',
'ldap_fail_authed' => 'O acesso LDAPfalou ao tentar os detalhes do dn e senha fornecidos',
'ldap_extension_not_installed' => 'As extensões LDAP PHP não estão instaladas',
'ldap_cannot_connect' => 'Não foi possível conectar ao servidor LDAP. Conexão inicial falhou',
'social_no_action_defined' => 'Nenhuma ação definida',
'social_account_in_use' => 'Essa conta :socialAccount já está em uso. Por favor, tente se logar usando a opção :socialAccount',
'social_account_email_in_use' => 'O e-mail :email já está e muso. Se você já tem uma conta você poderá se conectar a conta :socialAccount a partir das configurações de seu perfil.',
'social_account_existing' => 'Essa conta :socialAccount já está atrelada a esse perfil.',
'social_account_already_used_existing' => 'Essa conta :socialAccount já está sendo usada por outro usuário.',
'social_account_not_used' => 'Essa conta :socialAccount não está atrelada a nenhum usuário. Por favor, faça o link da conta com suas configurações de perfil. ',
'social_account_register_instructions' => 'Se você não tem uma conta, você poderá fazer o registro usando a opção :socialAccount',
'social_driver_not_found' => 'Social driver não encontrado',
'social_driver_not_configured' => 'Seus parâmetros socials de :socialAccount não estão configurados corretamente.',
// System
'path_not_writable' => 'O caminho de destino (:filePath) de upload de arquivo não possui permissão de escrita. Certifique-se que ele possui direitos de escrita no servidor.',
'cannot_get_image_from_url' => 'Não foi possivel capturar a imagem a partir de :url',
'cannot_create_thumbs' => 'O servidor não pôde criar as miniaturas de imagem. Por favor, verifique se a extensão GD PHP está instalada.',
'server_upload_limit' => 'O servidor não permite o upload de arquivos com esse tamanho. Por favor, tente fazer o upload de arquivos de menor tamanho.',
'image_upload_error' => 'Um erro aconteceu enquanto o servidor tentava efetuar o upload da imagem',
// Attachments
'attachment_page_mismatch' => 'Erro de \'Page mismatch\' durante a atualização do anexo',
// Pages
'page_draft_autosave_fail' => 'Falou ao tentar salvar o rascunho. Certifique-se que a conexão de internet está funcional antes de tentar salvar essa página',
// Entities
'entity_not_found' => 'Entidade não encontrada',
'book_not_found' => 'Livro não encontrado',
'page_not_found' => 'Página não encontrada',
'chapter_not_found' => 'Capítulo não encontrado',
'selected_book_not_found' => 'O livro selecionado não foi encontrado',
'selected_book_chapter_not_found' => 'O Livro selecionado ou Capítulo não foi encontrado',
'guests_cannot_save_drafts' => 'Convidados não podem salvar rascunhos',
// Users
'users_cannot_delete_only_admin' => 'Você não pode excluir o conteúdo, apenas o admin.',
'users_cannot_delete_guest' => 'Você não pode excluir o usuário convidado',
// Roles
'role_cannot_be_edited' => 'Esse perfil não poed ser editado',
'role_system_cannot_be_deleted' => 'Esse perfil é um perfil de sistema e não pode ser excluído',
'role_registration_default_cannot_delete' => 'Esse perfil não poderá se excluído enquando estiver registrado como o perfil padrão',
// Error pages
'404_page_not_found' => 'Página não encontrada',
'sorry_page_not_found' => 'Desculpe, a página que você está procurando não pôde ser encontrada.',
'return_home' => 'Retornar à página principal',
'error_occurred' => 'Um erro ocorreu',
'app_down' => ':appName está fora do ar no momento',
'back_soon' => 'Voltaremos em seguida.',
];
\ No newline at end of file
<?php
return [
/*
|--------------------------------------------------------------------------
| Pagination Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used by the paginator library to build
| the simple pagination links. You are free to change them to anything
| you want to customize your views to better match your application.
|
*/
'previous' => '&laquo; Anterior',
'next' => 'Próximo &raquo;',
];
<?php
return [
/*
|--------------------------------------------------------------------------
| Password Reminder Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are the default lines which match reasons
| that are given by the password broker for a password update attempt
| has failed, such as for an invalid token or invalid new password.
|
*/
'password' => 'Senhas devem ter ao menos 6 caraceres e combinar com os atributos mínimos para a senha.',
'user' => "Não pudemos encontrar um usuário com o e-mail fornecido.",
'token' => 'O token de reset de senha é inválido.',
'sent' => 'Enviamos para seu e-mail o link de reset de senha!',
'reset' => 'Sua senha foi resetada com sucesso!',
];