diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index 4f9f4c480..e7e75cc9f 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -1,11 +1,13 @@ ### 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 diff --git a/.gitignore b/.gitignore index 919b3e75d..15b034ad6 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,4 @@ _ide_helper.php /storage/debugbar .phpstorm.meta.php yarn.lock +/bin \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index e2eb5f511..0ad753ced 100644 --- a/.travis.yml +++ b/.travis.yml @@ -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 diff --git a/app/Chapter.php b/app/Chapter.php index cc5518b7a..dc23f5ebd 100644 --- a/app/Chapter.php +++ b/app/Chapter.php @@ -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); } /** diff --git a/app/Entity.php b/app/Entity.php index 186059f00..e8deddf0a 100644 --- a/app/Entity.php +++ b/app/Entity.php @@ -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); } } diff --git a/app/Http/Controllers/AttachmentController.php b/app/Http/Controllers/AttachmentController.php index 62be0b852..3c325d0fe 100644 --- a/app/Http/Controllers/AttachmentController.php +++ b/app/Http/Controllers/AttachmentController.php @@ -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')]); } } diff --git a/app/Http/Controllers/Auth/ForgotPasswordController.php b/app/Http/Controllers/Auth/ForgotPasswordController.php index 45e40e6fe..d1fbddc50 100644 --- a/app/Http/Controllers/Auth/ForgotPasswordController.php +++ b/app/Http/Controllers/Auth/ForgotPasswordController.php @@ -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)); } diff --git a/app/Http/Controllers/Auth/LoginController.php b/app/Http/Controllers/Auth/LoginController.php index c9d6a5496..e7eeb9bc1 100644 --- a/app/Http/Controllers/Auth/LoginController.php +++ b/app/Http/Controllers/Auth/LoginController.php @@ -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(); diff --git a/app/Http/Controllers/Auth/RegisterController.php b/app/Http/Controllers/Auth/RegisterController.php index d9bb500b4..8b0ef309a 100644 --- a/app/Http/Controllers/Auth/RegisterController.php +++ b/app/Http/Controllers/Auth/RegisterController.php @@ -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(); } diff --git a/app/Http/Controllers/Auth/ResetPasswordController.php b/app/Http/Controllers/Auth/ResetPasswordController.php index bd64793f9..eb678503d 100644 --- a/app/Http/Controllers/Auth/ResetPasswordController.php +++ b/app/Http/Controllers/Auth/ResetPasswordController.php @@ -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)); diff --git a/app/Http/Controllers/BookController.php b/app/Http/Controllers/BookController.php index 8ada59433..57ac486d5 100644 --- a/app/Http/Controllers/BookController.php +++ b/app/Http/Controllers/BookController.php @@ -1,34 +1,26 @@ 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()); } } diff --git a/app/Http/Controllers/ChapterController.php b/app/Http/Controllers/ChapterController.php index a3fb600fd..1760ee5c6 100644 --- a/app/Http/Controllers/ChapterController.php +++ b/app/Http/Controllers/ChapterController.php @@ -1,30 +1,26 @@ 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()); } } diff --git a/app/Http/Controllers/HomeController.php b/app/Http/Controllers/HomeController.php index 2fc64b236..f4706a5c4 100644 --- a/app/Http/Controllers/HomeController.php +++ b/app/Http/Controllers/HomeController.php @@ -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' + ]); + } + } diff --git a/app/Http/Controllers/ImageController.php b/app/Http/Controllers/ImageController.php index 621c23e85..77c320e07 100644 --- a/app/Http/Controllers/ImageController.php +++ b/app/Http/Controllers/ImageController.php @@ -1,6 +1,7 @@ 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')); } diff --git a/app/Http/Controllers/PageController.php b/app/Http/Controllers/PageController.php index c2d8e257c..4ed10d61e 100644 --- a/app/Http/Controllers/PageController.php +++ b/app/Http/Controllers/PageController.php @@ -2,40 +2,31 @@ use Activity; use BookStack\Exceptions\NotFoundException; +use BookStack\Repos\EntityRepo; use BookStack\Repos\UserRepo; use BookStack\Services\ExportService; use Carbon\Carbon; use Illuminate\Http\Request; -use BookStack\Http\Requests; -use BookStack\Repos\BookRepo; -use BookStack\Repos\ChapterRepo; -use BookStack\Repos\PageRepo; -use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; +use Illuminate\Http\Response; use Views; use GatherContent\Htmldiff\Htmldiff; class PageController extends Controller { - protected $pageRepo; - protected $bookRepo; - protected $chapterRepo; + protected $entityRepo; protected $exportService; protected $userRepo; /** * PageController constructor. - * @param PageRepo $pageRepo - * @param BookRepo $bookRepo - * @param ChapterRepo $chapterRepo + * @param EntityRepo $entityRepo * @param ExportService $exportService * @param UserRepo $userRepo */ - public function __construct(PageRepo $pageRepo, BookRepo $bookRepo, ChapterRepo $chapterRepo, ExportService $exportService, UserRepo $userRepo) + public function __construct(EntityRepo $entityRepo, ExportService $exportService, UserRepo $userRepo) { - $this->pageRepo = $pageRepo; - $this->bookRepo = $bookRepo; - $this->chapterRepo = $chapterRepo; + $this->entityRepo = $entityRepo; $this->exportService = $exportService; $this->userRepo = $userRepo; parent::__construct(); @@ -50,19 +41,19 @@ class PageController extends Controller */ public function create($bookSlug, $chapterSlug = null) { - $book = $this->bookRepo->getBySlug($bookSlug); - $chapter = $chapterSlug ? $this->chapterRepo->getBySlug($chapterSlug, $book->id) : null; + $book = $this->entityRepo->getBySlug('book', $bookSlug); + $chapter = $chapterSlug ? $this->entityRepo->getBySlug('chapter', $chapterSlug, $bookSlug) : null; $parent = $chapter ? $chapter : $book; $this->checkOwnablePermission('page-create', $parent); // Redirect to draft edit screen if signed in if ($this->signedIn) { - $draft = $this->pageRepo->getDraftPage($book, $chapter); + $draft = $this->entityRepo->getDraftPage($book, $chapter); return redirect($draft->getUrl()); } // Otherwise show edit view - $this->setPageTitle('Create New Page'); + $this->setPageTitle(trans('entities.pages_new')); return view('pages/guest-create', ['parent' => $parent]); } @@ -80,13 +71,13 @@ class PageController extends Controller 'name' => 'required|string|max:255' ]); - $book = $this->bookRepo->getBySlug($bookSlug); - $chapter = $chapterSlug ? $this->chapterRepo->getBySlug($chapterSlug, $book->id) : null; + $book = $this->entityRepo->getBySlug('book', $bookSlug); + $chapter = $chapterSlug ? $this->entityRepo->getBySlug('chapter', $chapterSlug, $bookSlug) : null; $parent = $chapter ? $chapter : $book; $this->checkOwnablePermission('page-create', $parent); - $page = $this->pageRepo->getDraftPage($book, $chapter); - $this->pageRepo->publishDraft($page, [ + $page = $this->entityRepo->getDraftPage($book, $chapter); + $this->entityRepo->publishPageDraft($page, [ 'name' => $request->get('name'), 'html' => '' ]); @@ -101,15 +92,14 @@ class PageController extends Controller */ public function editDraft($bookSlug, $pageId) { - $book = $this->bookRepo->getBySlug($bookSlug); - $draft = $this->pageRepo->getById($pageId, true); - $this->checkOwnablePermission('page-create', $book); - $this->setPageTitle('Edit Page Draft'); + $draft = $this->entityRepo->getById('page', $pageId, true); + $this->checkOwnablePermission('page-create', $draft->book); + $this->setPageTitle(trans('entities.pages_edit_draft')); $draftsEnabled = $this->signedIn; return view('pages/edit', [ 'page' => $draft, - 'book' => $book, + 'book' => $draft->book, 'isDraft' => true, 'draftsEnabled' => $draftsEnabled ]); @@ -119,6 +109,7 @@ class PageController extends Controller * Store a new page by changing a draft into a page. * @param Request $request * @param string $bookSlug + * @param int $pageId * @return Response */ public function store(Request $request, $bookSlug, $pageId) @@ -128,21 +119,21 @@ class PageController extends Controller ]); $input = $request->all(); - $book = $this->bookRepo->getBySlug($bookSlug); + $book = $this->entityRepo->getBySlug('book', $bookSlug); - $draftPage = $this->pageRepo->getById($pageId, true); + $draftPage = $this->entityRepo->getById('page', $pageId, true); $chapterId = intval($draftPage->chapter_id); - $parent = $chapterId !== 0 ? $this->chapterRepo->getById($chapterId) : $book; + $parent = $chapterId !== 0 ? $this->entityRepo->getById('chapter', $chapterId) : $book; $this->checkOwnablePermission('page-create', $parent); if ($parent->isA('chapter')) { - $input['priority'] = $this->chapterRepo->getNewPriority($parent); + $input['priority'] = $this->entityRepo->getNewChapterPriority($parent); } else { - $input['priority'] = $this->bookRepo->getNewPriority($parent); + $input['priority'] = $this->entityRepo->getNewBookPriority($parent); } - $page = $this->pageRepo->publishDraft($draftPage, $input); + $page = $this->entityRepo->publishPageDraft($draftPage, $input); Activity::add($page, 'page_create', $book->id); return redirect($page->getUrl()); @@ -150,33 +141,33 @@ class PageController extends Controller /** * Display the specified page. - * If the page is not found via the slug the - * revisions are searched for a match. + * If the page is not found via the slug the revisions are searched for a match. * @param string $bookSlug * @param string $pageSlug * @return Response */ public function show($bookSlug, $pageSlug) { - $book = $this->bookRepo->getBySlug($bookSlug); - try { - $page = $this->pageRepo->getBySlug($pageSlug, $book->id); + $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug); } catch (NotFoundException $e) { - $page = $this->pageRepo->findPageUsingOldSlug($pageSlug, $bookSlug); + $page = $this->entityRepo->getPageByOldSlug($pageSlug, $bookSlug); if ($page === null) abort(404); return redirect($page->getUrl()); } $this->checkOwnablePermission('page-view', $page); - $sidebarTree = $this->bookRepo->getChildren($book); - $pageNav = $this->pageRepo->getPageNav($page); + $pageContent = $this->entityRepo->renderPage($page); + $sidebarTree = $this->entityRepo->getBookChildren($page->book); + $pageNav = $this->entityRepo->getPageNav($pageContent); Views::add($page); $this->setPageTitle($page->getShortName()); - return view('pages/show', ['page' => $page, 'book' => $book, - 'current' => $page, 'sidebarTree' => $sidebarTree, 'pageNav' => $pageNav]); + return view('pages/show', [ + 'page' => $page,'book' => $page->book, + 'current' => $page, 'sidebarTree' => $sidebarTree, + 'pageNav' => $pageNav, 'pageContent' => $pageContent]); } /** @@ -186,7 +177,7 @@ class PageController extends Controller */ public function getPageAjax($pageId) { - $page = $this->pageRepo->getById($pageId); + $page = $this->entityRepo->getById('page', $pageId); return response()->json($page); } @@ -198,26 +189,25 @@ class PageController extends Controller */ public function edit($bookSlug, $pageSlug) { - $book = $this->bookRepo->getBySlug($bookSlug); - $page = $this->pageRepo->getBySlug($pageSlug, $book->id); + $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug); $this->checkOwnablePermission('page-update', $page); - $this->setPageTitle('Editing Page ' . $page->getShortName()); + $this->setPageTitle(trans('entities.pages_editing_named', ['pageName'=>$page->getShortName()])); $page->isDraft = false; // Check for active editing $warnings = []; - if ($this->pageRepo->isPageEditingActive($page, 60)) { - $warnings[] = $this->pageRepo->getPageEditingActiveMessage($page, 60); + if ($this->entityRepo->isPageEditingActive($page, 60)) { + $warnings[] = $this->entityRepo->getPageEditingActiveMessage($page, 60); } // Check for a current draft version for this user - if ($this->pageRepo->hasUserGotPageDraft($page, $this->currentUser->id)) { - $draft = $this->pageRepo->getUserPageDraft($page, $this->currentUser->id); + if ($this->entityRepo->hasUserGotPageDraft($page, $this->currentUser->id)) { + $draft = $this->entityRepo->getUserPageDraft($page, $this->currentUser->id); $page->name = $draft->name; $page->html = $draft->html; $page->markdown = $draft->markdown; $page->isDraft = true; - $warnings [] = $this->pageRepo->getUserPageDraftMessage($draft); + $warnings [] = $this->entityRepo->getUserPageDraftMessage($draft); } if (count($warnings) > 0) session()->flash('warning', implode("\n", $warnings)); @@ -225,7 +215,7 @@ class PageController extends Controller $draftsEnabled = $this->signedIn; return view('pages/edit', [ 'page' => $page, - 'book' => $book, + 'book' => $page->book, 'current' => $page, 'draftsEnabled' => $draftsEnabled ]); @@ -243,11 +233,10 @@ class PageController extends Controller $this->validate($request, [ 'name' => 'required|string|max:255' ]); - $book = $this->bookRepo->getBySlug($bookSlug); - $page = $this->pageRepo->getBySlug($pageSlug, $book->id); + $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug); $this->checkOwnablePermission('page-update', $page); - $this->pageRepo->updatePage($page, $book->id, $request->all()); - Activity::add($page, 'page_update', $book->id); + $this->entityRepo->updatePage($page, $page->book->id, $request->all()); + Activity::add($page, 'page_update', $page->book->id); return redirect($page->getUrl()); } @@ -259,27 +248,23 @@ class PageController extends Controller */ public function saveDraft(Request $request, $pageId) { - $page = $this->pageRepo->getById($pageId, true); + $page = $this->entityRepo->getById('page', $pageId, true); $this->checkOwnablePermission('page-update', $page); if (!$this->signedIn) { return response()->json([ 'status' => 'error', - 'message' => 'Guests cannot save drafts', + 'message' => trans('errors.guests_cannot_save_drafts'), ], 500); } - if ($page->draft) { - $draft = $this->pageRepo->updateDraftPage($page, $request->only(['name', 'html', 'markdown'])); - } else { - $draft = $this->pageRepo->saveUpdateDraft($page, $request->only(['name', 'html', 'markdown'])); - } + $draft = $this->entityRepo->updatePageDraft($page, $request->only(['name', 'html', 'markdown'])); $updateTime = $draft->updated_at->timestamp; $utcUpdateTimestamp = $updateTime + Carbon::createFromTimestamp(0)->offset; return response()->json([ 'status' => 'success', - 'message' => 'Draft saved at ', + 'message' => trans('entities.pages_edit_draft_save_at'), 'timestamp' => $utcUpdateTimestamp ]); } @@ -292,7 +277,7 @@ class PageController extends Controller */ public function redirectFromLink($pageId) { - $page = $this->pageRepo->getById($pageId); + $page = $this->entityRepo->getById('page', $pageId); return redirect($page->getUrl()); } @@ -304,11 +289,10 @@ class PageController extends Controller */ public function showDelete($bookSlug, $pageSlug) { - $book = $this->bookRepo->getBySlug($bookSlug); - $page = $this->pageRepo->getBySlug($pageSlug, $book->id); + $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug); $this->checkOwnablePermission('page-delete', $page); - $this->setPageTitle('Delete Page ' . $page->getShortName()); - return view('pages/delete', ['book' => $book, 'page' => $page, 'current' => $page]); + $this->setPageTitle(trans('entities.pages_delete_named', ['pageName'=>$page->getShortName()])); + return view('pages/delete', ['book' => $page->book, 'page' => $page, 'current' => $page]); } @@ -321,11 +305,10 @@ class PageController extends Controller */ public function showDeleteDraft($bookSlug, $pageId) { - $book = $this->bookRepo->getBySlug($bookSlug); - $page = $this->pageRepo->getById($pageId, true); + $page = $this->entityRepo->getById('page', $pageId, true); $this->checkOwnablePermission('page-update', $page); - $this->setPageTitle('Delete Draft Page ' . $page->getShortName()); - return view('pages/delete', ['book' => $book, 'page' => $page, 'current' => $page]); + $this->setPageTitle(trans('entities.pages_delete_draft_named', ['pageName'=>$page->getShortName()])); + return view('pages/delete', ['book' => $page->book, 'page' => $page, 'current' => $page]); } /** @@ -337,12 +320,12 @@ class PageController extends Controller */ public function destroy($bookSlug, $pageSlug) { - $book = $this->bookRepo->getBySlug($bookSlug); - $page = $this->pageRepo->getBySlug($pageSlug, $book->id); + $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug); + $book = $page->book; $this->checkOwnablePermission('page-delete', $page); Activity::addMessage('page_delete', $book->id, $page->name); - session()->flash('success', 'Page deleted'); - $this->pageRepo->destroy($page); + session()->flash('success', trans('entities.pages_delete_success')); + $this->entityRepo->destroyPage($page); return redirect($book->getUrl()); } @@ -355,11 +338,11 @@ class PageController extends Controller */ public function destroyDraft($bookSlug, $pageId) { - $book = $this->bookRepo->getBySlug($bookSlug); - $page = $this->pageRepo->getById($pageId, true); + $page = $this->entityRepo->getById('page', $pageId, true); + $book = $page->book; $this->checkOwnablePermission('page-update', $page); - session()->flash('success', 'Draft deleted'); - $this->pageRepo->destroy($page); + session()->flash('success', trans('entities.pages_delete_draft_success')); + $this->entityRepo->destroyPage($page); return redirect($book->getUrl()); } @@ -371,10 +354,9 @@ class PageController extends Controller */ public function showRevisions($bookSlug, $pageSlug) { - $book = $this->bookRepo->getBySlug($bookSlug); - $page = $this->pageRepo->getBySlug($pageSlug, $book->id); - $this->setPageTitle('Revisions For ' . $page->getShortName()); - return view('pages/revisions', ['page' => $page, 'book' => $book, 'current' => $page]); + $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug); + $this->setPageTitle(trans('entities.pages_revisions_named', ['pageName'=>$page->getShortName()])); + return view('pages/revisions', ['page' => $page, 'book' => $page->book, 'current' => $page]); } /** @@ -386,16 +368,15 @@ class PageController extends Controller */ public function showRevision($bookSlug, $pageSlug, $revisionId) { - $book = $this->bookRepo->getBySlug($bookSlug); - $page = $this->pageRepo->getBySlug($pageSlug, $book->id); - $revision = $this->pageRepo->getRevisionById($revisionId); + $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug); + $revision = $this->entityRepo->getById('page_revision', $revisionId, false); $page->fill($revision->toArray()); - $this->setPageTitle('Page Revision For ' . $page->getShortName()); + $this->setPageTitle(trans('entities.pages_revision_named', ['pageName'=>$page->getShortName()])); return view('pages/revision', [ 'page' => $page, - 'book' => $book, + 'book' => $page->book, ]); } @@ -408,20 +389,19 @@ class PageController extends Controller */ public function showRevisionChanges($bookSlug, $pageSlug, $revisionId) { - $book = $this->bookRepo->getBySlug($bookSlug); - $page = $this->pageRepo->getBySlug($pageSlug, $book->id); - $revision = $this->pageRepo->getRevisionById($revisionId); + $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug); + $revision = $this->entityRepo->getById('page_revision', $revisionId); $prev = $revision->getPrevious(); $prevContent = ($prev === null) ? '' : $prev->html; $diff = (new Htmldiff)->diff($prevContent, $revision->html); $page->fill($revision->toArray()); - $this->setPageTitle('Page Revision For ' . $page->getShortName()); + $this->setPageTitle(trans('entities.pages_revision_named', ['pageName'=>$page->getShortName()])); return view('pages/revision', [ 'page' => $page, - 'book' => $book, + 'book' => $page->book, 'diff' => $diff, ]); } @@ -435,11 +415,10 @@ class PageController extends Controller */ public function restoreRevision($bookSlug, $pageSlug, $revisionId) { - $book = $this->bookRepo->getBySlug($bookSlug); - $page = $this->pageRepo->getBySlug($pageSlug, $book->id); + $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug); $this->checkOwnablePermission('page-update', $page); - $page = $this->pageRepo->restoreRevision($page, $book, $revisionId); - Activity::add($page, 'page_restore', $book->id); + $page = $this->entityRepo->restorePageRevision($page, $page->book, $revisionId); + Activity::add($page, 'page_restore', $page->book->id); return redirect($page->getUrl()); } @@ -452,9 +431,9 @@ class PageController extends Controller */ public function exportPdf($bookSlug, $pageSlug) { - $book = $this->bookRepo->getBySlug($bookSlug); - $page = $this->pageRepo->getBySlug($pageSlug, $book->id); + $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug); $pdfContent = $this->exportService->pageToPdf($page); +// return $pdfContent; return response()->make($pdfContent, 200, [ 'Content-Type' => 'application/octet-stream', 'Content-Disposition' => 'attachment; filename="' . $pageSlug . '.pdf' @@ -469,8 +448,7 @@ class PageController extends Controller */ public function exportHtml($bookSlug, $pageSlug) { - $book = $this->bookRepo->getBySlug($bookSlug); - $page = $this->pageRepo->getBySlug($pageSlug, $book->id); + $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug); $containedHtml = $this->exportService->pageToContainedHtml($page); return response()->make($containedHtml, 200, [ 'Content-Type' => 'application/octet-stream', @@ -486,8 +464,7 @@ class PageController extends Controller */ public function exportPlainText($bookSlug, $pageSlug) { - $book = $this->bookRepo->getBySlug($bookSlug); - $page = $this->pageRepo->getBySlug($pageSlug, $book->id); + $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug); $containedHtml = $this->exportService->pageToPlainText($page); return response()->make($containedHtml, 200, [ 'Content-Type' => 'application/octet-stream', @@ -501,9 +478,9 @@ class PageController extends Controller */ public function showRecentlyCreated() { - $pages = $this->pageRepo->getRecentlyCreatedPaginated(20)->setPath(baseUrl('/pages/recently-created')); + $pages = $this->entityRepo->getRecentlyCreatedPaginated('page', 20)->setPath(baseUrl('/pages/recently-created')); return view('pages/detailed-listing', [ - 'title' => 'Recently Created Pages', + 'title' => trans('entities.recently_created_pages'), 'pages' => $pages ]); } @@ -514,9 +491,9 @@ class PageController extends Controller */ public function showRecentlyUpdated() { - $pages = $this->pageRepo->getRecentlyUpdatedPaginated(20)->setPath(baseUrl('/pages/recently-updated')); + $pages = $this->entityRepo->getRecentlyUpdatedPaginated('page', 20)->setPath(baseUrl('/pages/recently-updated')); return view('pages/detailed-listing', [ - 'title' => 'Recently Updated Pages', + 'title' => trans('entities.recently_updated_pages'), 'pages' => $pages ]); } @@ -529,8 +506,7 @@ class PageController extends Controller */ public function showRestrict($bookSlug, $pageSlug) { - $book = $this->bookRepo->getBySlug($bookSlug); - $page = $this->pageRepo->getBySlug($pageSlug, $book->id); + $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug); $this->checkOwnablePermission('restrictions-manage', $page); $roles = $this->userRepo->getRestrictableRoles(); return view('pages/restrictions', [ @@ -548,11 +524,10 @@ class PageController extends Controller */ public function showMove($bookSlug, $pageSlug) { - $book = $this->bookRepo->getBySlug($bookSlug); - $page = $this->pageRepo->getBySlug($pageSlug, $book->id); + $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug); $this->checkOwnablePermission('page-update', $page); return view('pages/move', [ - 'book' => $book, + 'book' => $page->book, 'page' => $page ]); } @@ -567,8 +542,7 @@ class PageController extends Controller */ public function move($bookSlug, $pageSlug, Request $request) { - $book = $this->bookRepo->getBySlug($bookSlug); - $page = $this->pageRepo->getBySlug($pageSlug, $book->id); + $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug); $this->checkOwnablePermission('page-update', $page); $entitySelection = $request->get('entity_selection', null); @@ -580,22 +554,17 @@ class PageController extends Controller $entityType = $stringExploded[0]; $entityId = intval($stringExploded[1]); - $parent = false; - if ($entityType == 'chapter') { - $parent = $this->chapterRepo->getById($entityId); - } else if ($entityType == 'book') { - $parent = $this->bookRepo->getById($entityId); - } - - if ($parent === false || $parent === null) { - session()->flash('The selected Book or Chapter was not found'); + try { + $parent = $this->entityRepo->getById($entityType, $entityId); + } catch (\Exception $e) { + session()->flash(trans('entities.selected_book_chapter_not_found')); return redirect()->back(); } - $this->pageRepo->changePageParent($page, $parent); + $this->entityRepo->changePageParent($page, $parent); Activity::add($page, 'page_move', $page->book->id); - session()->flash('success', sprintf('Page moved to "%s"', $parent->name)); + session()->flash('success', trans('entities.pages_move_success', ['parentName' => $parent->name])); return redirect($page->getUrl()); } @@ -609,11 +578,10 @@ class PageController extends Controller */ public function restrict($bookSlug, $pageSlug, Request $request) { - $book = $this->bookRepo->getBySlug($bookSlug); - $page = $this->pageRepo->getBySlug($pageSlug, $book->id); + $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug); $this->checkOwnablePermission('restrictions-manage', $page); - $this->pageRepo->updateEntityPermissionsFromRequest($request, $page); - session()->flash('success', 'Page Permissions Updated'); + $this->entityRepo->updateEntityPermissionsFromRequest($request, $page); + session()->flash('success', trans('entities.pages_permissions_success')); return redirect($page->getUrl()); } diff --git a/app/Http/Controllers/PermissionController.php b/app/Http/Controllers/PermissionController.php index ed430c0b7..cd064e7e8 100644 --- a/app/Http/Controllers/PermissionController.php +++ b/app/Http/Controllers/PermissionController.php @@ -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'); } } diff --git a/app/Http/Controllers/SearchController.php b/app/Http/Controllers/SearchController.php index 58ad737c4..37aaccece 100644 --- a/app/Http/Controllers/SearchController.php +++ b/app/Http/Controllers/SearchController.php @@ -1,34 +1,22 @@ -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) { diff --git a/app/Http/Controllers/SettingController.php b/app/Http/Controllers/SettingController.php index 65135eda3..70a12631a 100644 --- a/app/Http/Controllers/SettingController.php +++ b/app/Http/Controllers/SettingController.php @@ -1,8 +1,7 @@ flash('success', 'Settings Saved'); + session()->flash('success', trans('settings.settings_save_success')); return redirect('/settings'); } diff --git a/app/Http/Controllers/TagController.php b/app/Http/Controllers/TagController.php index c8a356541..24bdcdb1c 100644 --- a/app/Http/Controllers/TagController.php +++ b/app/Http/Controllers/TagController.php @@ -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) { @@ -29,29 +30,10 @@ class TagController extends Controller return response()->json($tags); } - /** - * 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) { diff --git a/app/Http/Controllers/UserController.php b/app/Http/Controllers/UserController.php index 18ef1a671..c98d5f87e 100644 --- a/app/Http/Controllers/UserController.php +++ b/app/Http/Controllers/UserController.php @@ -1,13 +1,8 @@ - $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'); } diff --git a/app/Http/Kernel.php b/app/Http/Kernel.php index f1d95f5c0..c55cc9ab8 100644 --- a/app/Http/Kernel.php +++ b/app/Http/Kernel.php @@ -1,6 +1,4 @@ - [ 'throttle:60,1', diff --git a/app/Http/Middleware/Authenticate.php b/app/Http/Middleware/Authenticate.php index 8461ed0ba..b78016688 100644 --- a/app/Http/Middleware/Authenticate.php +++ b/app/Http/Middleware/Authenticate.php @@ -4,8 +4,6 @@ namespace BookStack\Http\Middleware; use Closure; use Illuminate\Contracts\Auth\Guard; -use BookStack\Exceptions\UserRegistrationException; -use Setting; class Authenticate { diff --git a/app/Http/Middleware/Localization.php b/app/Http/Middleware/Localization.php new file mode 100644 index 000000000..31cb5d9a2 --- /dev/null +++ b/app/Http/Middleware/Localization.php @@ -0,0 +1,23 @@ +getUser(user(), 'language', $defaultLang); + app()->setLocale($locale); + Carbon::setLocale($locale); + return $next($request); + } +} diff --git a/app/Http/Middleware/RedirectIfAuthenticated.php b/app/Http/Middleware/RedirectIfAuthenticated.php index 2b3c64695..c27df7af4 100644 --- a/app/Http/Middleware/RedirectIfAuthenticated.php +++ b/app/Http/Middleware/RedirectIfAuthenticated.php @@ -1,6 +1,4 @@ -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')); } } diff --git a/app/Page.php b/app/Page.php index 3ee9e90f4..b24e7778a 100644 --- a/app/Page.php +++ b/app/Page.php @@ -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 diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 4665bf6c7..40a1eef3d 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -1,6 +1,7 @@ getMimeType(), $imageMimes); }); - } /** diff --git a/app/Repos/BookRepo.php b/app/Repos/BookRepo.php deleted file mode 100644 index 7bb91f472..000000000 --- a/app/Repos/BookRepo.php +++ /dev/null @@ -1,295 +0,0 @@ -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', "\$0", $book->getExcerpt(100)); - $book->searchSnippet = $result; - } - return $books; - } - -} \ No newline at end of file diff --git a/app/Repos/ChapterRepo.php b/app/Repos/ChapterRepo.php deleted file mode 100644 index 4c13b9aaf..000000000 --- a/app/Repos/ChapterRepo.php +++ /dev/null @@ -1,226 +0,0 @@ -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', "\$0", $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 diff --git a/app/Repos/EntityRepo.php b/app/Repos/EntityRepo.php index 7ecfb758c..f1428735c 100644 --- a/app/Repos/EntityRepo.php +++ b/app/Repos/EntityRepo.php @@ -3,11 +3,16 @@ use BookStack\Book; use BookStack\Chapter; use BookStack\Entity; +use BookStack\Exceptions\NotFoundException; use BookStack\Page; +use BookStack\PageRevision; +use BookStack\Services\AttachmentService; use BookStack\Services\PermissionService; -use BookStack\User; +use BookStack\Services\ViewService; +use Carbon\Carbon; +use DOMDocument; +use DOMXPath; use Illuminate\Support\Collection; -use Illuminate\Support\Facades\Log; class EntityRepo { @@ -27,11 +32,32 @@ class EntityRepo */ public $page; + /** + * @var PageRevision + */ + protected $pageRevision; + + /** + * Base entity instances keyed by type + * @var []Entity + */ + protected $entities; + /** * @var PermissionService */ protected $permissionService; + /** + * @var ViewService + */ + protected $viewService; + + /** + * @var TagRepo + */ + protected $tagRepo; + /** * Acceptable operators to be used in a query * @var array @@ -40,26 +66,163 @@ class EntityRepo /** * EntityService constructor. + * @param Book $book + * @param Chapter $chapter + * @param Page $page + * @param PageRevision $pageRevision + * @param ViewService $viewService + * @param PermissionService $permissionService + * @param TagRepo $tagRepo */ - public function __construct() + public function __construct( + Book $book, Chapter $chapter, Page $page, PageRevision $pageRevision, + ViewService $viewService, PermissionService $permissionService, TagRepo $tagRepo + ) { - $this->book = app(Book::class); - $this->chapter = app(Chapter::class); - $this->page = app(Page::class); - $this->permissionService = app(PermissionService::class); + $this->book = $book; + $this->chapter = $chapter; + $this->page = $page; + $this->pageRevision = $pageRevision; + $this->entities = [ + 'page' => $this->page, + 'chapter' => $this->chapter, + 'book' => $this->book, + 'page_revision' => $this->pageRevision + ]; + $this->viewService = $viewService; + $this->permissionService = $permissionService; + $this->tagRepo = $tagRepo; } /** - * Get the latest books added to the system. + * Get an entity instance via type. + * @param $type + * @return Entity + */ + protected function getEntity($type) + { + return $this->entities[strtolower($type)]; + } + + /** + * Base query for searching entities via permission system + * @param string $type + * @param bool $allowDrafts + * @return \Illuminate\Database\Query\Builder + */ + protected function entityQuery($type, $allowDrafts = false) + { + $q = $this->permissionService->enforceEntityRestrictions($type, $this->getEntity($type), 'view'); + if (strtolower($type) === 'page' && !$allowDrafts) { + $q = $q->where('draft', '=', false); + } + return $q; + } + + /** + * Check if an entity with the given id exists. + * @param $type + * @param $id + * @return bool + */ + public function exists($type, $id) + { + return $this->entityQuery($type)->where('id', '=', $id)->exists(); + } + + /** + * Get an entity by ID + * @param string $type + * @param integer $id + * @param bool $allowDrafts + * @return Entity + */ + public function getById($type, $id, $allowDrafts = false) + { + return $this->entityQuery($type, $allowDrafts)->find($id); + } + + /** + * Get an entity by its url slug. + * @param string $type + * @param string $slug + * @param string|bool $bookSlug + * @return Entity + * @throws NotFoundException + */ + public function getBySlug($type, $slug, $bookSlug = false) + { + $q = $this->entityQuery($type)->where('slug', '=', $slug); + + if (strtolower($type) === 'chapter' || strtolower($type) === 'page') { + $q = $q->where('book_id', '=', function($query) use ($bookSlug) { + $query->select('id') + ->from($this->book->getTable()) + ->where('slug', '=', $bookSlug)->limit(1); + }); + } + $entity = $q->first(); + if ($entity === null) throw new NotFoundException(trans('errors.' . strtolower($type) . '_not_found')); + return $entity; + } + + + /** + * Search through page revisions and retrieve the last page in the + * current book that has a slug equal to the one given. + * @param string $pageSlug + * @param string $bookSlug + * @return null|Page + */ + public function getPageByOldSlug($pageSlug, $bookSlug) + { + $revision = $this->pageRevision->where('slug', '=', $pageSlug) + ->whereHas('page', function ($query) { + $this->permissionService->enforceEntityRestrictions('page', $query); + }) + ->where('type', '=', 'version') + ->where('book_slug', '=', $bookSlug) + ->orderBy('created_at', 'desc') + ->with('page')->first(); + return $revision !== null ? $revision->page : null; + } + + /** + * Get all entities of a type limited by count unless count if false. + * @param string $type + * @param integer|bool $count + * @return Collection + */ + public function getAll($type, $count = 20) + { + $q = $this->entityQuery($type)->orderBy('name', 'asc'); + if ($count !== false) $q = $q->take($count); + return $q->get(); + } + + /** + * Get all entities in a paginated format + * @param $type + * @param int $count + * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator + */ + public function getAllPaginated($type, $count = 10) + { + return $this->entityQuery($type)->orderBy('name', 'asc')->paginate($count); + } + + /** + * Get the most recently created entities of the given type. + * @param string $type * @param int $count * @param int $page - * @param bool $additionalQuery - * @return + * @param bool|callable $additionalQuery */ - public function getRecentlyCreatedBooks($count = 20, $page = 0, $additionalQuery = false) + public function getRecentlyCreated($type, $count = 20, $page = 0, $additionalQuery = false) { - $query = $this->permissionService->enforceBookRestrictions($this->book) + $query = $this->permissionService->enforceEntityRestrictions($type, $this->getEntity($type)) ->orderBy('created_at', 'desc'); + if (strtolower($type) === 'page') $query = $query->where('draft', '=', false); if ($additionalQuery !== false && is_callable($additionalQuery)) { $additionalQuery($query); } @@ -67,45 +230,17 @@ class EntityRepo } /** - * Get the most recently updated books. - * @param $count - * @param int $page - * @return mixed - */ - public function getRecentlyUpdatedBooks($count = 20, $page = 0) - { - return $this->permissionService->enforceBookRestrictions($this->book) - ->orderBy('updated_at', 'desc')->skip($page * $count)->take($count)->get(); - } - - /** - * Get the latest pages added to the system. + * Get the most recently updated entities of the given type. + * @param string $type * @param int $count * @param int $page - * @param bool $additionalQuery - * @return + * @param bool|callable $additionalQuery */ - public function getRecentlyCreatedPages($count = 20, $page = 0, $additionalQuery = false) + public function getRecentlyUpdated($type, $count = 20, $page = 0, $additionalQuery = false) { - $query = $this->permissionService->enforcePageRestrictions($this->page) - ->orderBy('created_at', 'desc')->where('draft', '=', false); - if ($additionalQuery !== false && is_callable($additionalQuery)) { - $additionalQuery($query); - } - return $query->with('book')->skip($page * $count)->take($count)->get(); - } - - /** - * Get the latest chapters added to the system. - * @param int $count - * @param int $page - * @param bool $additionalQuery - * @return - */ - public function getRecentlyCreatedChapters($count = 20, $page = 0, $additionalQuery = false) - { - $query = $this->permissionService->enforceChapterRestrictions($this->chapter) - ->orderBy('created_at', 'desc'); + $query = $this->permissionService->enforceEntityRestrictions($type, $this->getEntity($type)) + ->orderBy('updated_at', 'desc'); + if (strtolower($type) === 'page') $query = $query->where('draft', '=', false); if ($additionalQuery !== false && is_callable($additionalQuery)) { $additionalQuery($query); } @@ -113,16 +248,51 @@ class EntityRepo } /** - * Get the most recently updated pages. - * @param $count + * Get the most recently viewed entities. + * @param string|bool $type + * @param int $count * @param int $page * @return mixed */ - public function getRecentlyUpdatedPages($count = 20, $page = 0) + public function getRecentlyViewed($type, $count = 10, $page = 0) { - return $this->permissionService->enforcePageRestrictions($this->page) - ->where('draft', '=', false) - ->orderBy('updated_at', 'desc')->with('book')->skip($page * $count)->take($count)->get(); + $filter = is_bool($type) ? false : $this->getEntity($type); + return $this->viewService->getUserRecentlyViewed($count, $page, $filter); + } + + /** + * Get the latest pages added to the system with pagination. + * @param string $type + * @param int $count + * @return mixed + */ + public function getRecentlyCreatedPaginated($type, $count = 20) + { + return $this->entityQuery($type)->orderBy('created_at', 'desc')->paginate($count); + } + + /** + * Get the latest pages added to the system with pagination. + * @param string $type + * @param int $count + * @return mixed + */ + public function getRecentlyUpdatedPaginated($type, $count = 20) + { + return $this->entityQuery($type)->orderBy('updated_at', 'desc')->paginate($count); + } + + /** + * Get the most popular entities base on all views. + * @param string|bool $type + * @param int $count + * @param int $page + * @return mixed + */ + public function getPopular($type, $count = 10, $page = 0) + { + $filter = is_bool($type) ? false : $this->getEntity($type); + return $this->viewService->getPopular($count, $page, $filter); } /** @@ -138,6 +308,163 @@ class EntityRepo ->skip($count * $page)->take($count)->get(); } + /** + * 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 getBookChildren(Book $book, $filterDrafts = false) + { + $q = $this->permissionService->bookChildrenQuery($book->id, $filterDrafts)->get(); + $entities = []; + $parents = []; + $tree = []; + + foreach ($q as $index => $rawEntity) { + if ($rawEntity->entity_type === 'BookStack\\Page') { + $entities[$index] = $this->page->newFromBuilder($rawEntity); + } else if ($rawEntity->entity_type === 'BookStack\\Chapter') { + $entities[$index] = $this->chapter->newFromBuilder($rawEntity); + $key = $entities[$index]->entity_type . ':' . $entities[$index]->id; + $parents[$key] = $entities[$index]; + $parents[$key]->setAttribute('pages', collect()); + } + if ($entities[$index]->chapter_id === 0) $tree[] = $entities[$index]; + $entities[$index]->book = $book; + } + + foreach ($entities as $entity) { + if ($entity->chapter_id === 0) continue; + $parentKey = 'BookStack\\Chapter:' . $entity->chapter_id; + $chapter = $parents[$parentKey]; + $chapter->pages->push($entity); + } + + return collect($tree); + } + + /** + * Get the child items for a chapter sorted by priority but + * with draft items floated to the top. + * @param Chapter $chapter + */ + public function getChapterChildren(Chapter $chapter) + { + return $this->permissionService->enforceEntityRestrictions('page', $chapter->pages()) + ->orderBy('draft', 'DESC')->orderBy('priority', 'ASC')->get(); + } + + /** + * Search entities of a type via a given query. + * @param string $type + * @param string $term + * @param array $whereTerms + * @param int $count + * @param array $paginationAppends + * @return mixed + */ + public function getBySearch($type, $term, $whereTerms = [], $count = 20, $paginationAppends = []) + { + $terms = $this->prepareSearchTerms($term); + $q = $this->permissionService->enforceEntityRestrictions($type, $this->getEntity($type)->fullTextSearchQuery($terms, $whereTerms)); + $q = $this->addAdvancedSearchQueries($q, $term); + $entities = $q->paginate($count)->appends($paginationAppends); + $words = join('|', explode(' ', preg_quote(trim($term), '/'))); + + // Highlight page content + if ($type === 'page') { + //lookahead/behind assertions ensures cut between words + $s = '\s\x00-/:-@\[-`{-~'; //character set for start/end of words + + foreach ($entities as $page) { + preg_match_all('#(?<=[' . $s . ']).{1,30}((' . $words . ').{1,30})+(?=[' . $s . '])#uis', $page->text, $matches, PREG_SET_ORDER); + //delimiter between occurrences + $results = []; + foreach ($matches as $line) { + $results[] = htmlspecialchars($line[0], 0, 'UTF-8'); + } + $matchLimit = 6; + if (count($results) > $matchLimit) $results = array_slice($results, 0, $matchLimit); + $result = join('... ', $results); + + //highlight + $result = preg_replace('#' . $words . '#iu', "\$0", $result); + if (strlen($result) < 5) $result = $page->getExcerpt(80); + + $page->searchSnippet = $result; + } + return $entities; + } + + // Highlight chapter/book content + foreach ($entities as $entity) { + //highlight + $result = preg_replace('#' . $words . '#iu', "\$0", $entity->getExcerpt(100)); + $entity->searchSnippet = $result; + } + return $entities; + } + + /** + * Get the next sequential priority for a new child element in the given book. + * @param Book $book + * @return int + */ + public function getNewBookPriority(Book $book) + { + $lastElem = $this->getBookChildren($book)->pop(); + return $lastElem ? $lastElem->priority + 1 : 0; + } + + /** + * Get a new priority for a new page to be added to the given chapter. + * @param Chapter $chapter + * @return int + */ + public function getNewChapterPriority(Chapter $chapter) + { + $lastPage = $chapter->pages('DESC')->first(); + return $lastPage !== null ? $lastPage->priority + 1 : 0; + } + + /** + * Find a suitable slug for an entity. + * @param string $type + * @param string $name + * @param bool|integer $currentId + * @param bool|integer $bookId Only pass if type is not a book + * @return string + */ + public function findSuitableSlug($type, $name, $currentId = false, $bookId = false) + { + $slug = $this->nameToSlug($name); + while ($this->slugExists($type, $slug, $currentId, $bookId)) { + $slug .= '-' . substr(md5(rand(1, 500)), 0, 3); + } + return $slug; + } + + /** + * Check if a slug already exists in the database. + * @param string $type + * @param string $slug + * @param bool|integer $currentId + * @param bool|integer $bookId + * @return bool + */ + protected function slugExists($type, $slug, $currentId = false, $bookId = false) + { + $query = $this->getEntity($type)->where('slug', '=', $slug); + if (strtolower($type) === 'page' || strtolower($type) === 'chapter') { + $query = $query->where('book_id', '=', $bookId); + } + if ($currentId) $query = $query->where('id', '!=', $currentId); + return $query->count() > 0; + } + /** * Updates entity restrictions from a request * @param $request @@ -260,6 +587,81 @@ class EntityRepo return $query; } + /** + * Create a new entity from request input. + * Used for books and chapters. + * @param string $type + * @param array $input + * @param bool|Book $book + * @return Entity + */ + public function createFromInput($type, $input = [], $book = false) + { + $isChapter = strtolower($type) === 'chapter'; + $entity = $this->getEntity($type)->newInstance($input); + $entity->slug = $this->findSuitableSlug($type, $entity->name, false, $isChapter ? $book->id : false); + $entity->created_by = user()->id; + $entity->updated_by = user()->id; + $isChapter ? $book->chapters()->save($entity) : $entity->save(); + $this->permissionService->buildJointPermissionsForEntity($entity); + return $entity; + } + + /** + * Update entity details from request input. + * Use for books and chapters + * @param string $type + * @param Entity $entityModel + * @param array $input + * @return Entity + */ + public function updateFromInput($type, Entity $entityModel, $input = []) + { + if ($entityModel->name !== $input['name']) { + $entityModel->slug = $this->findSuitableSlug($type, $input['name'], $entityModel->id); + } + $entityModel->fill($input); + $entityModel->updated_by = user()->id; + $entityModel->save(); + $this->permissionService->buildJointPermissionsForEntity($entityModel); + return $entityModel; + } + + /** + * Change the book that an entity belongs to. + * @param string $type + * @param integer $newBookId + * @param Entity $entity + * @param bool $rebuildPermissions + * @return Entity + */ + public function changeBook($type, $newBookId, Entity $entity, $rebuildPermissions = false) + { + $entity->book_id = $newBookId; + // Update related activity + foreach ($entity->activity as $activity) { + $activity->book_id = $newBookId; + $activity->save(); + } + $entity->slug = $this->findSuitableSlug($type, $entity->name, $entity->id, $newBookId); + $entity->save(); + + // Update all child pages if a chapter + if (strtolower($type) === 'chapter') { + foreach ($entity->pages as $page) { + $this->changeBook('page', $newBookId, $page, false); + } + } + + // Update permissions if applicable + if ($rebuildPermissions) { + $entity->load('book'); + $this->permissionService->buildJointPermissionsForEntity($entity->book); + } + + return $entity; + } + /** * Alias method to update the book jointPermissions in the PermissionService. * @param Collection $collection collection on entities @@ -282,6 +684,518 @@ class EntityRepo return $slug; } + /** + * Publish a draft page to make it a normal page. + * Sets the slug and updates the content. + * @param Page $draftPage + * @param array $input + * @return Page + */ + public function publishPageDraft(Page $draftPage, array $input) + { + $draftPage->fill($input); + + // Save page tags if present + if (isset($input['tags'])) { + $this->tagRepo->saveTagsToEntity($draftPage, $input['tags']); + } + + $draftPage->slug = $this->findSuitableSlug('page', $draftPage->name, false, $draftPage->book->id); + $draftPage->html = $this->formatHtml($input['html']); + $draftPage->text = strip_tags($draftPage->html); + $draftPage->draft = false; + + $draftPage->save(); + $this->savePageRevision($draftPage, trans('entities.pages_initial_revision')); + + return $draftPage; + } + + /** + * Saves a page revision into the system. + * @param Page $page + * @param null|string $summary + * @return PageRevision + */ + public function savePageRevision(Page $page, $summary = null) + { + $revision = $this->pageRevision->newInstance($page->toArray()); + if (setting('app-editor') !== 'markdown') $revision->markdown = ''; + $revision->page_id = $page->id; + $revision->slug = $page->slug; + $revision->book_slug = $page->book->slug; + $revision->created_by = user()->id; + $revision->created_at = $page->updated_at; + $revision->type = 'version'; + $revision->summary = $summary; + $revision->save(); + + // Clear old revisions + if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) { + $this->pageRevision->where('page_id', '=', $page->id) + ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete(); + } + + return $revision; + } + + /** + * Formats a page's html to be tagged correctly + * within the system. + * @param string $htmlText + * @return string + */ + protected function formatHtml($htmlText) + { + if ($htmlText == '') return $htmlText; + libxml_use_internal_errors(true); + $doc = new DOMDocument(); + $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8')); + + $container = $doc->documentElement; + $body = $container->childNodes->item(0); + $childNodes = $body->childNodes; + + // Ensure no duplicate ids are used + $idArray = []; + + foreach ($childNodes as $index => $childNode) { + /** @var \DOMElement $childNode */ + if (get_class($childNode) !== 'DOMElement') continue; + + // Overwrite id if not a BookStack custom id + if ($childNode->hasAttribute('id')) { + $id = $childNode->getAttribute('id'); + if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) { + $idArray[] = $id; + continue; + }; + } + + // Create an unique id for the element + // Uses the content as a basis to ensure output is the same every time + // the same content is passed through. + $contentId = 'bkmrk-' . substr(strtolower(preg_replace('/\s+/', '-', trim($childNode->nodeValue))), 0, 20); + $newId = urlencode($contentId); + $loopIndex = 0; + while (in_array($newId, $idArray)) { + $newId = urlencode($contentId . '-' . $loopIndex); + $loopIndex++; + } + + $childNode->setAttribute('id', $newId); + $idArray[] = $newId; + } + + // Generate inner html as a string + $html = ''; + foreach ($childNodes as $childNode) { + $html .= $doc->saveHTML($childNode); + } + + return $html; + } + + + /** + * Render the page for viewing, Parsing and performing features such as page transclusion. + * @param Page $page + * @return mixed|string + */ + public function renderPage(Page $page) + { + $content = $page->html; + $matches = []; + preg_match_all("/{{@\s?([0-9].*?)}}/", $content, $matches); + if (count($matches[0]) === 0) return $content; + + foreach ($matches[1] as $index => $includeId) { + $splitInclude = explode('#', $includeId, 2); + $pageId = intval($splitInclude[0]); + if (is_nan($pageId)) continue; + + $page = $this->getById('page', $pageId); + if ($page === null) { + $content = str_replace($matches[0][$index], '', $content); + continue; + } + + if (count($splitInclude) === 1) { + $content = str_replace($matches[0][$index], $page->html, $content); + continue; + } + + $doc = new DOMDocument(); + $doc->loadHTML(mb_convert_encoding(''.$page->html.'', 'HTML-ENTITIES', 'UTF-8')); + $matchingElem = $doc->getElementById($splitInclude[1]); + if ($matchingElem === null) { + $content = str_replace($matches[0][$index], '', $content); + continue; + } + $innerContent = ''; + foreach ($matchingElem->childNodes as $childNode) { + $innerContent .= $doc->saveHTML($childNode); + } + $content = str_replace($matches[0][$index], trim($innerContent), $content); + } + + return $content; + } + + /** + * Get a new draft page instance. + * @param Book $book + * @param Chapter|bool $chapter + * @return Page + */ + public function getDraftPage(Book $book, $chapter = false) + { + $page = $this->page->newInstance(); + $page->name = trans('entities.pages_initial_name'); + $page->created_by = user()->id; + $page->updated_by = user()->id; + $page->draft = true; + + if ($chapter) $page->chapter_id = $chapter->id; + + $book->pages()->save($page); + $this->permissionService->buildJointPermissionsForEntity($page); + return $page; + } + + /** + * Search for image usage within page content. + * @param $imageString + * @return mixed + */ + public function searchForImage($imageString) + { + $pages = $this->entityQuery('page')->where('html', 'like', '%' . $imageString . '%')->get(); + foreach ($pages as $page) { + $page->url = $page->getUrl(); + $page->html = ''; + $page->text = ''; + } + return count($pages) > 0 ? $pages : false; + } + + /** + * Parse the headers on the page to get a navigation menu + * @param String $pageContent + * @return array + */ + public function getPageNav($pageContent) + { + if ($pageContent == '') return []; + libxml_use_internal_errors(true); + $doc = new DOMDocument(); + $doc->loadHTML(mb_convert_encoding($pageContent, 'HTML-ENTITIES', 'UTF-8')); + $xPath = new DOMXPath($doc); + $headers = $xPath->query("//h1|//h2|//h3|//h4|//h5|//h6"); + + if (is_null($headers)) return []; + + $tree = collect([]); + foreach ($headers as $header) { + $text = $header->nodeValue; + $tree->push([ + 'nodeName' => strtolower($header->nodeName), + 'level' => intval(str_replace('h', '', $header->nodeName)), + 'link' => '#' . $header->getAttribute('id'), + 'text' => strlen($text) > 30 ? substr($text, 0, 27) . '...' : $text + ]); + } + + // Normalise headers if only smaller headers have been used + if (count($tree) > 0) { + $minLevel = $tree->pluck('level')->min(); + $tree = $tree->map(function($header) use ($minLevel) { + $header['level'] -= ($minLevel - 2); + return $header; + }); + } + return $tree->toArray(); + } + + /** + * Updates a page with any fillable data and saves it into the database. + * @param Page $page + * @param int $book_id + * @param array $input + * @return Page + */ + public function updatePage(Page $page, $book_id, $input) + { + // Hold the old details to compare later + $oldHtml = $page->html; + $oldName = $page->name; + + // Prevent slug being updated if no name change + if ($page->name !== $input['name']) { + $page->slug = $this->findSuitableSlug('page', $input['name'], $page->id, $book_id); + } + + // Save page tags if present + if (isset($input['tags'])) { + $this->tagRepo->saveTagsToEntity($page, $input['tags']); + } + + // Update with new details + $userId = user()->id; + $page->fill($input); + $page->html = $this->formatHtml($input['html']); + $page->text = strip_tags($page->html); + if (setting('app-editor') !== 'markdown') $page->markdown = ''; + $page->updated_by = $userId; + $page->save(); + + // Remove all update drafts for this user & page. + $this->userUpdatePageDraftsQuery($page, $userId)->delete(); + + // Save a revision after updating + if ($oldHtml !== $input['html'] || $oldName !== $input['name'] || $input['summary'] !== null) { + $this->savePageRevision($page, $input['summary']); + } + + return $page; + } + + /** + * The base query for getting user update drafts. + * @param Page $page + * @param $userId + * @return mixed + */ + protected function userUpdatePageDraftsQuery(Page $page, $userId) + { + return $this->pageRevision->where('created_by', '=', $userId) + ->where('type', 'update_draft') + ->where('page_id', '=', $page->id) + ->orderBy('created_at', 'desc'); + } + + /** + * Checks whether a user has a draft version of a particular page or not. + * @param Page $page + * @param $userId + * @return bool + */ + public function hasUserGotPageDraft(Page $page, $userId) + { + return $this->userUpdatePageDraftsQuery($page, $userId)->count() > 0; + } + + /** + * Get the latest updated draft revision for a particular page and user. + * @param Page $page + * @param $userId + * @return mixed + */ + public function getUserPageDraft(Page $page, $userId) + { + return $this->userUpdatePageDraftsQuery($page, $userId)->first(); + } + + /** + * Get the notification message that informs the user that they are editing a draft page. + * @param PageRevision $draft + * @return string + */ + public function getUserPageDraftMessage(PageRevision $draft) + { + $message = trans('entities.pages_editing_draft_notification', ['timeDiff' => $draft->updated_at->diffForHumans()]); + if ($draft->page->updated_at->timestamp <= $draft->updated_at->timestamp) return $message; + return $message . "\n" . trans('entities.pages_draft_edited_notification'); + } + + /** + * Check if a page is being actively editing. + * Checks for edits since last page updated. + * Passing in a minuted range will check for edits + * within the last x minutes. + * @param Page $page + * @param null $minRange + * @return bool + */ + public function isPageEditingActive(Page $page, $minRange = null) + { + $draftSearch = $this->activePageEditingQuery($page, $minRange); + return $draftSearch->count() > 0; + } + + /** + * A query to check for active update drafts on a particular page. + * @param Page $page + * @param null $minRange + * @return mixed + */ + protected function activePageEditingQuery(Page $page, $minRange = null) + { + $query = $this->pageRevision->where('type', '=', 'update_draft') + ->where('page_id', '=', $page->id) + ->where('updated_at', '>', $page->updated_at) + ->where('created_by', '!=', user()->id) + ->with('createdBy'); + + if ($minRange !== null) { + $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange)); + } + + return $query; + } + + /** + * Restores a revision's content back into a page. + * @param Page $page + * @param Book $book + * @param int $revisionId + * @return Page + */ + public function restorePageRevision(Page $page, Book $book, $revisionId) + { + $this->savePageRevision($page); + $revision = $this->getById('page_revision', $revisionId); + $page->fill($revision->toArray()); + $page->slug = $this->findSuitableSlug('page', $page->name, $page->id, $book->id); + $page->text = strip_tags($page->html); + $page->updated_by = user()->id; + $page->save(); + return $page; + } + + + /** + * Save a page update draft. + * @param Page $page + * @param array $data + * @return PageRevision|Page + */ + public function updatePageDraft(Page $page, $data = []) + { + // If the page itself is a draft simply update that + if ($page->draft) { + $page->fill($data); + if (isset($data['html'])) { + $page->text = strip_tags($data['html']); + } + $page->save(); + return $page; + } + + // Otherwise save the data to a revision + $userId = user()->id; + $drafts = $this->userUpdatePageDraftsQuery($page, $userId)->get(); + + if ($drafts->count() > 0) { + $draft = $drafts->first(); + } else { + $draft = $this->pageRevision->newInstance(); + $draft->page_id = $page->id; + $draft->slug = $page->slug; + $draft->book_slug = $page->book->slug; + $draft->created_by = $userId; + $draft->type = 'update_draft'; + } + + $draft->fill($data); + if (setting('app-editor') !== 'markdown') $draft->markdown = ''; + + $draft->save(); + return $draft; + } + + /** + * Get a notification message concerning the editing activity on a particular page. + * @param Page $page + * @param null $minRange + * @return string + */ + public function getPageEditingActiveMessage(Page $page, $minRange = null) + { + $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get(); + + $userMessage = $pageDraftEdits->count() > 1 ? trans('entities.pages_draft_edit_active.start_a', ['count' => $pageDraftEdits->count()]): trans('entities.pages_draft_edit_active.start_b', ['userName' => $pageDraftEdits->first()->createdBy->name]); + $timeMessage = $minRange === null ? trans('entities.pages_draft_edit_active.time_a') : trans('entities.pages_draft_edit_active.time_b', ['minCount'=>$minRange]); + return trans('entities.pages_draft_edit_active.message', ['start' => $userMessage, 'time' => $timeMessage]); + } + + /** + * Change the page's parent to the given entity. + * @param Page $page + * @param Entity $parent + */ + public function changePageParent(Page $page, Entity $parent) + { + $book = $parent->isA('book') ? $parent : $parent->book; + $page->chapter_id = $parent->isA('chapter') ? $parent->id : 0; + $page->save(); + if ($page->book->id !== $book->id) { + $page = $this->changeBook('page', $book->id, $page); + } + $page->load('book'); + $this->permissionService->buildJointPermissionsForEntity($book); + } + + /** + * Destroy the provided book and all its child entities. + * @param Book $book + */ + public function destroyBook(Book $book) + { + foreach ($book->pages as $page) { + $this->destroyPage($page); + } + foreach ($book->chapters as $chapter) { + $this->destroyChapter($chapter); + } + \Activity::removeEntity($book); + $book->views()->delete(); + $book->permissions()->delete(); + $this->permissionService->deleteJointPermissionsForEntity($book); + $book->delete(); + } + + /** + * Destroy a chapter and its relations. + * @param Chapter $chapter + */ + public function destroyChapter(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(); + } + + /** + * Destroy a given page along with its dependencies. + * @param Page $page + */ + public function destroyPage(Page $page) + { + \Activity::removeEntity($page); + $page->views()->delete(); + $page->tags()->delete(); + $page->revisions()->delete(); + $page->permissions()->delete(); + $this->permissionService->deleteJointPermissionsForEntity($page); + + // Delete Attached Files + $attachmentService = app(AttachmentService::class); + foreach ($page->attachments as $attachment) { + $attachmentService->deleteFile($attachment); + } + + $page->delete(); + } + } diff --git a/app/Repos/PageRepo.php b/app/Repos/PageRepo.php deleted file mode 100644 index e6d713f77..000000000 --- a/app/Repos/PageRepo.php +++ /dev/null @@ -1,666 +0,0 @@ -pageRevision = $pageRevision; - $this->tagRepo = $tagRepo; - parent::__construct(); - } - - /** - * Base query for getting pages, Takes restrictions into account. - * @param bool $allowDrafts - * @return mixed - */ - private function pageQuery($allowDrafts = false) - { - $query = $this->permissionService->enforcePageRestrictions($this->page, 'view'); - if (!$allowDrafts) { - $query = $query->where('draft', '=', false); - } - return $query; - } - - /** - * Get a page via a specific ID. - * @param $id - * @param bool $allowDrafts - * @return Page - */ - public function getById($id, $allowDrafts = false) - { - return $this->pageQuery($allowDrafts)->findOrFail($id); - } - - /** - * Get a page identified by the given slug. - * @param $slug - * @param $bookId - * @return Page - * @throws NotFoundException - */ - public function getBySlug($slug, $bookId) - { - $page = $this->pageQuery()->where('slug', '=', $slug)->where('book_id', '=', $bookId)->first(); - if ($page === null) throw new NotFoundException('Page not found'); - return $page; - } - - /** - * Search through page revisions and retrieve - * the last page in the current book that - * has a slug equal to the one given. - * @param $pageSlug - * @param $bookSlug - * @return null | Page - */ - public function findPageUsingOldSlug($pageSlug, $bookSlug) - { - $revision = $this->pageRevision->where('slug', '=', $pageSlug) - ->whereHas('page', function ($query) { - $this->permissionService->enforcePageRestrictions($query); - }) - ->where('type', '=', 'version') - ->where('book_slug', '=', $bookSlug)->orderBy('created_at', 'desc') - ->with('page')->first(); - return $revision !== null ? $revision->page : null; - } - - /** - * Get a new Page instance from the given input. - * @param $input - * @return Page - */ - public function newFromInput($input) - { - $page = $this->page->fill($input); - return $page; - } - - /** - * Count the pages with a particular slug within a book. - * @param $slug - * @param $bookId - * @return mixed - */ - public function countBySlug($slug, $bookId) - { - return $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId)->count(); - } - - /** - * Publish a draft page to make it a normal page. - * Sets the slug and updates the content. - * @param Page $draftPage - * @param array $input - * @return Page - */ - public function publishDraft(Page $draftPage, array $input) - { - $draftPage->fill($input); - - // Save page tags if present - if (isset($input['tags'])) { - $this->tagRepo->saveTagsToEntity($draftPage, $input['tags']); - } - - $draftPage->slug = $this->findSuitableSlug($draftPage->name, $draftPage->book->id); - $draftPage->html = $this->formatHtml($input['html']); - $draftPage->text = strip_tags($draftPage->html); - $draftPage->draft = false; - - $draftPage->save(); - $this->saveRevision($draftPage, 'Initial Publish'); - - return $draftPage; - } - - /** - * Get a new draft page instance. - * @param Book $book - * @param Chapter|bool $chapter - * @return static - */ - public function getDraftPage(Book $book, $chapter = false) - { - $page = $this->page->newInstance(); - $page->name = 'New Page'; - $page->created_by = user()->id; - $page->updated_by = user()->id; - $page->draft = true; - - if ($chapter) $page->chapter_id = $chapter->id; - - $book->pages()->save($page); - $this->permissionService->buildJointPermissionsForEntity($page); - return $page; - } - - /** - * Parse te headers on the page to get a navigation menu - * @param Page $page - * @return array - */ - public function getPageNav(Page $page) - { - if ($page->html == '') return null; - libxml_use_internal_errors(true); - $doc = new DOMDocument(); - $doc->loadHTML(mb_convert_encoding($page->html, 'HTML-ENTITIES', 'UTF-8')); - $xPath = new DOMXPath($doc); - $headers = $xPath->query("//h1|//h2|//h3|//h4|//h5|//h6"); - - if (is_null($headers)) return null; - - $tree = []; - foreach ($headers as $header) { - $text = $header->nodeValue; - $tree[] = [ - 'nodeName' => strtolower($header->nodeName), - 'level' => intval(str_replace('h', '', $header->nodeName)), - 'link' => '#' . $header->getAttribute('id'), - 'text' => strlen($text) > 30 ? substr($text, 0, 27) . '...' : $text - ]; - } - return $tree; - } - - /** - * Formats a page's html to be tagged correctly - * within the system. - * @param string $htmlText - * @return string - */ - protected function formatHtml($htmlText) - { - if ($htmlText == '') return $htmlText; - libxml_use_internal_errors(true); - $doc = new DOMDocument(); - $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8')); - - $container = $doc->documentElement; - $body = $container->childNodes->item(0); - $childNodes = $body->childNodes; - - // Ensure no duplicate ids are used - $idArray = []; - - foreach ($childNodes as $index => $childNode) { - /** @var \DOMElement $childNode */ - if (get_class($childNode) !== 'DOMElement') continue; - - // Overwrite id if not a BookStack custom id - if ($childNode->hasAttribute('id')) { - $id = $childNode->getAttribute('id'); - if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) { - $idArray[] = $id; - continue; - }; - } - - // Create an unique id for the element - // Uses the content as a basis to ensure output is the same every time - // the same content is passed through. - $contentId = 'bkmrk-' . substr(strtolower(preg_replace('/\s+/', '-', trim($childNode->nodeValue))), 0, 20); - $newId = urlencode($contentId); - $loopIndex = 0; - while (in_array($newId, $idArray)) { - $newId = urlencode($contentId . '-' . $loopIndex); - $loopIndex++; - } - - $childNode->setAttribute('id', $newId); - $idArray[] = $newId; - } - - // Generate inner html as a string - $html = ''; - foreach ($childNodes as $childNode) { - $html .= $doc->saveHTML($childNode); - } - - return $html; - } - - - /** - * Gets pages by a search term. - * Highlights page content for showing in results. - * @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); - $pageQuery = $this->permissionService->enforcePageRestrictions($this->page->fullTextSearchQuery(['name', 'text'], $terms, $whereTerms)); - $pageQuery = $this->addAdvancedSearchQueries($pageQuery, $term); - $pages = $pageQuery->paginate($count)->appends($paginationAppends); - - // Add highlights to page text. - $words = join('|', explode(' ', preg_quote(trim($term), '/'))); - //lookahead/behind assertions ensures cut between words - $s = '\s\x00-/:-@\[-`{-~'; //character set for start/end of words - - foreach ($pages as $page) { - preg_match_all('#(?<=[' . $s . ']).{1,30}((' . $words . ').{1,30})+(?=[' . $s . '])#uis', $page->text, $matches, PREG_SET_ORDER); - //delimiter between occurrences - $results = []; - foreach ($matches as $line) { - $results[] = htmlspecialchars($line[0], 0, 'UTF-8'); - } - $matchLimit = 6; - if (count($results) > $matchLimit) { - $results = array_slice($results, 0, $matchLimit); - } - $result = join('... ', $results); - - //highlight - $result = preg_replace('#' . $words . '#iu', "\$0", $result); - if (strlen($result) < 5) { - $result = $page->getExcerpt(80); - } - $page->searchSnippet = $result; - } - return $pages; - } - - /** - * Search for image usage. - * @param $imageString - * @return mixed - */ - public function searchForImage($imageString) - { - $pages = $this->pageQuery()->where('html', 'like', '%' . $imageString . '%')->get(); - foreach ($pages as $page) { - $page->url = $page->getUrl(); - $page->html = ''; - $page->text = ''; - } - return count($pages) > 0 ? $pages : false; - } - - /** - * Updates a page with any fillable data and saves it into the database. - * @param Page $page - * @param int $book_id - * @param string $input - * @return Page - */ - public function updatePage(Page $page, $book_id, $input) - { - // Hold the old details to compare later - $oldHtml = $page->html; - $oldName = $page->name; - - // Prevent slug being updated if no name change - if ($page->name !== $input['name']) { - $page->slug = $this->findSuitableSlug($input['name'], $book_id, $page->id); - } - - // Save page tags if present - if (isset($input['tags'])) { - $this->tagRepo->saveTagsToEntity($page, $input['tags']); - } - - // Update with new details - $userId = user()->id; - $page->fill($input); - $page->html = $this->formatHtml($input['html']); - $page->text = strip_tags($page->html); - if (setting('app-editor') !== 'markdown') $page->markdown = ''; - $page->updated_by = $userId; - $page->save(); - - // Remove all update drafts for this user & page. - $this->userUpdateDraftsQuery($page, $userId)->delete(); - - // Save a revision after updating - if ($oldHtml !== $input['html'] || $oldName !== $input['name'] || $input['summary'] !== null) { - $this->saveRevision($page, $input['summary']); - } - - return $page; - } - - /** - * Restores a revision's content back into a page. - * @param Page $page - * @param Book $book - * @param int $revisionId - * @return Page - */ - public function restoreRevision(Page $page, Book $book, $revisionId) - { - $this->saveRevision($page); - $revision = $this->getRevisionById($revisionId); - $page->fill($revision->toArray()); - $page->slug = $this->findSuitableSlug($page->name, $book->id, $page->id); - $page->text = strip_tags($page->html); - $page->updated_by = user()->id; - $page->save(); - return $page; - } - - /** - * Saves a page revision into the system. - * @param Page $page - * @param null|string $summary - * @return $this - */ - public function saveRevision(Page $page, $summary = null) - { - $revision = $this->pageRevision->newInstance($page->toArray()); - if (setting('app-editor') !== 'markdown') $revision->markdown = ''; - $revision->page_id = $page->id; - $revision->slug = $page->slug; - $revision->book_slug = $page->book->slug; - $revision->created_by = user()->id; - $revision->created_at = $page->updated_at; - $revision->type = 'version'; - $revision->summary = $summary; - $revision->save(); - - // Clear old revisions - if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) { - $this->pageRevision->where('page_id', '=', $page->id) - ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete(); - } - - return $revision; - } - - /** - * Save a page update draft. - * @param Page $page - * @param array $data - * @return PageRevision - */ - public function saveUpdateDraft(Page $page, $data = []) - { - $userId = user()->id; - $drafts = $this->userUpdateDraftsQuery($page, $userId)->get(); - - if ($drafts->count() > 0) { - $draft = $drafts->first(); - } else { - $draft = $this->pageRevision->newInstance(); - $draft->page_id = $page->id; - $draft->slug = $page->slug; - $draft->book_slug = $page->book->slug; - $draft->created_by = $userId; - $draft->type = 'update_draft'; - } - - $draft->fill($data); - if (setting('app-editor') !== 'markdown') $draft->markdown = ''; - - $draft->save(); - return $draft; - } - - /** - * Update a draft page. - * @param Page $page - * @param array $data - * @return Page - */ - public function updateDraftPage(Page $page, $data = []) - { - $page->fill($data); - - if (isset($data['html'])) { - $page->text = strip_tags($data['html']); - } - - $page->save(); - return $page; - } - - /** - * The base query for getting user update drafts. - * @param Page $page - * @param $userId - * @return mixed - */ - private function userUpdateDraftsQuery(Page $page, $userId) - { - return $this->pageRevision->where('created_by', '=', $userId) - ->where('type', 'update_draft') - ->where('page_id', '=', $page->id) - ->orderBy('created_at', 'desc'); - } - - /** - * Checks whether a user has a draft version of a particular page or not. - * @param Page $page - * @param $userId - * @return bool - */ - public function hasUserGotPageDraft(Page $page, $userId) - { - return $this->userUpdateDraftsQuery($page, $userId)->count() > 0; - } - - /** - * Get the latest updated draft revision for a particular page and user. - * @param Page $page - * @param $userId - * @return mixed - */ - public function getUserPageDraft(Page $page, $userId) - { - return $this->userUpdateDraftsQuery($page, $userId)->first(); - } - - /** - * Get the notification message that informs the user that they are editing a draft page. - * @param PageRevision $draft - * @return string - */ - public function getUserPageDraftMessage(PageRevision $draft) - { - $message = 'You are currently editing a draft that was last saved ' . $draft->updated_at->diffForHumans() . '.'; - if ($draft->page->updated_at->timestamp > $draft->updated_at->timestamp) { - $message .= "\n This page has been updated by since that time. It is recommended that you discard this draft."; - } - return $message; - } - - /** - * Check if a page is being actively editing. - * Checks for edits since last page updated. - * Passing in a minuted range will check for edits - * within the last x minutes. - * @param Page $page - * @param null $minRange - * @return bool - */ - public function isPageEditingActive(Page $page, $minRange = null) - { - $draftSearch = $this->activePageEditingQuery($page, $minRange); - return $draftSearch->count() > 0; - } - - /** - * Get a notification message concerning the editing activity on - * a particular page. - * @param Page $page - * @param null $minRange - * @return string - */ - public function getPageEditingActiveMessage(Page $page, $minRange = null) - { - $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get(); - $userMessage = $pageDraftEdits->count() > 1 ? $pageDraftEdits->count() . ' users have' : $pageDraftEdits->first()->createdBy->name . ' has'; - $timeMessage = $minRange === null ? 'since the page was last updated' : 'in the last ' . $minRange . ' minutes'; - $message = '%s started editing this page %s. Take care not to overwrite each other\'s updates!'; - return sprintf($message, $userMessage, $timeMessage); - } - - /** - * A query to check for active update drafts on a particular page. - * @param Page $page - * @param null $minRange - * @return mixed - */ - private function activePageEditingQuery(Page $page, $minRange = null) - { - $query = $this->pageRevision->where('type', '=', 'update_draft') - ->where('page_id', '=', $page->id) - ->where('updated_at', '>', $page->updated_at) - ->where('created_by', '!=', user()->id) - ->with('createdBy'); - - if ($minRange !== null) { - $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange)); - } - - return $query; - } - - /** - * Gets a single revision via it's id. - * @param $id - * @return PageRevision - */ - public function getRevisionById($id) - { - return $this->pageRevision->findOrFail($id); - } - - /** - * Checks if a slug exists within a book already. - * @param $slug - * @param $bookId - * @param bool|false $currentId - * @return bool - */ - public function doesSlugExist($slug, $bookId, $currentId = false) - { - $query = $this->page->where('slug', '=', $slug)->where('book_id', '=', $bookId); - if ($currentId) $query = $query->where('id', '!=', $currentId); - return $query->count() > 0; - } - - /** - * Changes the related book for the specified page. - * Changes the book id of any relations to the page that store the book id. - * @param int $bookId - * @param Page $page - * @return Page - */ - public function changeBook($bookId, Page $page) - { - $page->book_id = $bookId; - foreach ($page->activity as $activity) { - $activity->book_id = $bookId; - $activity->save(); - } - $page->slug = $this->findSuitableSlug($page->name, $bookId, $page->id); - $page->save(); - return $page; - } - - - /** - * Change the page's parent to the given entity. - * @param Page $page - * @param Entity $parent - */ - public function changePageParent(Page $page, Entity $parent) - { - $book = $parent->isA('book') ? $parent : $parent->book; - $page->chapter_id = $parent->isA('chapter') ? $parent->id : 0; - $page->save(); - $page = $this->changeBook($book->id, $page); - $page->load('book'); - $this->permissionService->buildJointPermissionsForEntity($book); - } - - /** - * Gets a suitable slug for the resource - * @param string $name - * @param int $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; - } - - /** - * Destroy a given page along with its dependencies. - * @param $page - */ - public function destroy(Page $page) - { - Activity::removeEntity($page); - $page->views()->delete(); - $page->tags()->delete(); - $page->revisions()->delete(); - $page->permissions()->delete(); - $this->permissionService->deleteJointPermissionsForEntity($page); - - // Delete AttachedFiles - $attachmentService = app(AttachmentService::class); - foreach ($page->attachments as $attachment) { - $attachmentService->deleteFile($attachment); - } - - $page->delete(); - } - - /** - * Get the latest pages added to the system. - * @param $count - * @return mixed - */ - public function getRecentlyCreatedPaginated($count = 20) - { - return $this->pageQuery()->orderBy('created_at', 'desc')->paginate($count); - } - - /** - * Get the latest pages added to the system. - * @param $count - * @return mixed - */ - public function getRecentlyUpdatedPaginated($count = 20) - { - return $this->pageQuery()->orderBy('updated_at', 'desc')->paginate($count); - } - -} diff --git a/app/Repos/PermissionsRepo.php b/app/Repos/PermissionsRepo.php index 24497c911..aa58d1718 100644 --- a/app/Repos/PermissionsRepo.php +++ b/app/Repos/PermissionsRepo.php @@ -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) { diff --git a/app/Repos/TagRepo.php b/app/Repos/TagRepo.php index 6d0857f8b..c6350db1a 100644 --- a/app/Repos/TagRepo.php +++ b/app/Repos/TagRepo.php @@ -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) { diff --git a/app/Repos/UserRepo.php b/app/Repos/UserRepo.php index ab3716fca..c3546a442 100644 --- a/app/Repos/UserRepo.php +++ b/app/Repos/UserRepo.php @@ -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); }) ]; diff --git a/app/Services/ActivityService.php b/app/Services/ActivityService.php index e41036238..2368ba10a 100644 --- a/app/Services/ActivityService.php +++ b/app/Services/ActivityService.php @@ -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); } diff --git a/app/Services/AttachmentService.php b/app/Services/AttachmentService.php index e0ee3a04d..592d67e63 100644 --- a/app/Services/AttachmentService.php +++ b/app/Services/AttachmentService.php @@ -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; } diff --git a/app/Services/EmailConfirmationService.php b/app/Services/EmailConfirmationService.php index d4ec1e976..8eb52708c 100644 --- a/app/Services/EmailConfirmationService.php +++ b/app/Services/EmailConfirmationService.php @@ -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); diff --git a/app/Services/ExportService.php b/app/Services/ExportService.php index 14084d320..880bc54ad 100644 --- a/app/Services/ExportService.php +++ b/app/Services/ExportService.php @@ -1,11 +1,22 @@ 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. diff --git a/app/Services/ImageService.php b/app/Services/ImageService.php index dfe2cf453..e34b3fb2b 100644 --- a/app/Services/ImageService.php +++ b/app/Services/ImageService.php @@ -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; } diff --git a/app/Services/Ldap.php b/app/Services/Ldap.php index 196e46a2f..9c3bec327 100644 --- a/app/Services/Ldap.php +++ b/app/Services/Ldap.php @@ -94,4 +94,4 @@ class Ldap return ldap_bind($ldapConnection, $bindRdn, $bindPassword); } -} \ No newline at end of file +} diff --git a/app/Services/LdapService.php b/app/Services/LdapService.php index b7f101ad2..f8a4b88bb 100644 --- a/app/Services/LdapService.php +++ b/app/Services/LdapService.php @@ -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 diff --git a/app/Services/PermissionService.php b/app/Services/PermissionService.php index bb78f0b0a..39a2c38be 100644 --- a/app/Services/PermissionService.php +++ b/app/Services/PermissionService.php @@ -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); - return $this->enforceEntityRestrictions($query, $action); - } + 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); + } - /** - * 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; diff --git a/app/Services/SettingService.php b/app/Services/SettingService.php index bf5fa918e..40094a513 100644 --- a/app/Services/SettingService.php +++ b/app/Services/SettingService.php @@ -1,6 +1,7 @@ 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. @@ -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; } @@ -118,6 +124,16 @@ class SettingService return $setting !== null; } + /** + * 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 @@ -135,6 +151,28 @@ class SettingService return true; } + /** + * 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 @@ -150,6 +188,16 @@ class SettingService return true; } + /** + * 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 diff --git a/app/Services/SocialAuthService.php b/app/Services/SocialAuthService.php index d76a7231b..5edd4cad7 100644 --- a/app/Services/SocialAuthService.php +++ b/app/Services/SocialAuthService.php @@ -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()); } diff --git a/app/Services/ViewService.php b/app/Services/ViewService.php index 1a9ee5f70..3285745ce 100644 --- a/app/Services/ViewService.php +++ b/app/Services/ViewService.php @@ -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'); diff --git a/app/User.php b/app/User.php index 09b189cbb..afcd9af70 100644 --- a/app/User.php +++ b/app/User.php @@ -74,6 +74,16 @@ class User extends Model implements AuthenticatableContract, CanResetPasswordCon return $this->roles->pluck('name')->contains($role); } + /** + * 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 @@ -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; } /** diff --git a/app/helpers.php b/app/helpers.php index b5be0fd11..6decb08e9 100644 --- a/app/helpers.php +++ b/app/helpers.php @@ -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); } diff --git a/composer.json b/composer.json index 7d4b5e62b..5a8fd67ae 100644 --- a/composer.json +++ b/composer.json @@ -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", diff --git a/composer.lock b/composer.lock index 74a090288..dcde9d9c6 100644 --- a/composer.lock +++ b/composer.lock @@ -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", @@ -255,6 +255,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", @@ -997,6 +1049,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", diff --git a/config/app.php b/config/app.php index 786f005ac..0c3e1e71c 100644 --- a/config/app.php +++ b/config/app.php @@ -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, /** diff --git a/config/setting-defaults.php b/config/setting-defaults.php index c681bb7f5..db35023d5 100644 --- a/config/setting-defaults.php +++ b/config/setting-defaults.php @@ -6,6 +6,7 @@ return [ 'app-name' => 'BookStack', + 'app-logo' => '', 'app-name-header' => true, 'app-editor' => 'wysiwyg', 'app-color' => '#0288D1', diff --git a/config/snappy.php b/config/snappy.php new file mode 100644 index 000000000..73f21fd30 --- /dev/null +++ b/config/snappy.php @@ -0,0 +1,18 @@ + [ + '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' => [], + ], +]; diff --git a/database/factories/ModelFactory.php b/database/factories/ModelFactory.php index 3820d5b59..43e214386 100644 --- a/database/factories/ModelFactory.php +++ b/database/factories/ModelFactory.php @@ -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 diff --git a/database/migrations/2017_01_21_163556_create_cache_table.php b/database/migrations/2017_01_21_163556_create_cache_table.php new file mode 100644 index 000000000..1f7761c2b --- /dev/null +++ b/database/migrations/2017_01_21_163556_create_cache_table.php @@ -0,0 +1,32 @@ +string('key')->unique(); + $table->text('value'); + $table->integer('expiration'); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('cache'); + } +} diff --git a/database/migrations/2017_01_21_163602_create_sessions_table.php b/database/migrations/2017_01_21_163602_create_sessions_table.php new file mode 100644 index 000000000..56e76d6df --- /dev/null +++ b/database/migrations/2017_01_21_163602_create_sessions_table.php @@ -0,0 +1,35 @@ +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'); + } +} diff --git a/package.json b/package.json index 30f288d45..b0805c918 100644 --- a/package.json +++ b/package.json @@ -1,8 +1,9 @@ { "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" } } diff --git a/phpunit.xml b/phpunit.xml index 72e06a3fc..2e07cdbf8 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -22,6 +22,7 @@ + diff --git a/public/ZeroClipboard.swf b/public/ZeroClipboard.swf deleted file mode 100644 index 8bad6a3e3..000000000 Binary files a/public/ZeroClipboard.swf and /dev/null differ diff --git a/readme.md b/readme.md index 5d3e79a2e..63d43e4b7 100644 --- a/readme.md +++ b/readme.md @@ -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. diff --git a/resources/assets/js/controllers.js b/resources/assets/js/controllers.js index 9d7f7ad70..0d57b09ad 100644 --- a/resources/assets/js/controllers.js +++ b/resources/assets/js/controllers.js @@ -2,6 +2,8 @@ import moment from 'moment'; import 'moment/locale/en-gb'; +import editorOptions from "./pages/page-form"; + moment.locale('en-gb'); export default function (ngApp, events) { @@ -23,14 +25,14 @@ export default function (ngApp, events) { $scope.searching = false; $scope.searchTerm = ''; - var page = 0; - var previousClickTime = 0; - var previousClickImage = 0; - var dataLoaded = false; - var callback = false; + let page = 0; + let previousClickTime = 0; + let previousClickImage = 0; + let dataLoaded = false; + let callback = false; - var preSearchImages = []; - var preSearchHasMore = false; + let preSearchImages = []; + let preSearchHasMore = false; /** * Used by dropzone to get the endpoint to upload to. @@ -62,7 +64,7 @@ export default function (ngApp, events) { $scope.$apply(() => { $scope.images.unshift(data); }); - events.emit('success', 'Image uploaded'); + events.emit('success', trans('components.image_upload_success')); }; /** @@ -79,9 +81,9 @@ export default function (ngApp, events) { * @param image */ $scope.imageSelect = function (image) { - var dblClickTime = 300; - var currentTime = Date.now(); - var timeDiff = currentTime - previousClickTime; + let dblClickTime = 300; + let currentTime = Date.now(); + let timeDiff = currentTime - previousClickTime; if (timeDiff < dblClickTime && image.id === previousClickImage) { // If double click @@ -137,22 +139,21 @@ export default function (ngApp, events) { $('#image-manager').find('.overlay').fadeOut(240); }; - var baseUrl = window.baseUrl('/images/' + $scope.imageType + '/all/'); + let baseUrl = window.baseUrl('/images/' + $scope.imageType + '/all/'); /** * Fetch the list image data from the server. */ function fetchData() { - var url = baseUrl + page + '?'; - var components = {}; + let url = baseUrl + page + '?'; + let components = {}; if ($scope.uploadedTo) components['page_id'] = $scope.uploadedTo; if ($scope.searching) components['term'] = $scope.searchTerm; - var urlQueryString = Object.keys(components).map((key) => { + url += Object.keys(components).map((key) => { return key + '=' + encodeURIComponent(components[key]); }).join('&'); - url += urlQueryString; $http.get(url).then((response) => { $scope.images = $scope.images.concat(response.data.images); @@ -205,13 +206,13 @@ export default function (ngApp, events) { */ $scope.saveImageDetails = function (event) { event.preventDefault(); - var url = window.baseUrl('/images/update/' + $scope.selectedImage.id); + let url = window.baseUrl('/images/update/' + $scope.selectedImage.id); $http.put(url, this.selectedImage).then(response => { - events.emit('success', 'Image details updated'); + events.emit('success', trans('components.image_update_success')); }, (response) => { if (response.status === 422) { - var errors = response.data; - var message = ''; + let errors = response.data; + let message = ''; Object.keys(errors).forEach((key) => { message += errors[key].join('\n'); }); @@ -230,13 +231,13 @@ export default function (ngApp, events) { */ $scope.deleteImage = function (event) { event.preventDefault(); - var force = $scope.dependantPages !== false; - var url = window.baseUrl('/images/' + $scope.selectedImage.id); + let force = $scope.dependantPages !== false; + let url = window.baseUrl('/images/' + $scope.selectedImage.id); if (force) url += '?force=true'; $http.delete(url).then((response) => { $scope.images.splice($scope.images.indexOf($scope.selectedImage), 1); $scope.selectedImage = false; - events.emit('success', 'Image successfully deleted'); + events.emit('success', trans('components.image_delete_success')); }, (response) => { // Pages failure if (response.status === 400) { @@ -266,11 +267,11 @@ export default function (ngApp, events) { $scope.searchBook = function (e) { e.preventDefault(); - var term = $scope.searchTerm; + let term = $scope.searchTerm; if (term.length == 0) return; $scope.searching = true; $scope.searchResults = ''; - var searchUrl = window.baseUrl('/search/book/' + $attrs.bookId); + let searchUrl = window.baseUrl('/search/book/' + $attrs.bookId); searchUrl += '?term=' + encodeURIComponent(term); $http.get(searchUrl).then((response) => { $scope.searchResults = $sce.trustAsHtml(response.data); @@ -294,27 +295,27 @@ export default function (ngApp, events) { ngApp.controller('PageEditController', ['$scope', '$http', '$attrs', '$interval', '$timeout', '$sce', function ($scope, $http, $attrs, $interval, $timeout, $sce) { - $scope.editorOptions = require('./pages/page-form'); + $scope.editorOptions = editorOptions(); $scope.editContent = ''; $scope.draftText = ''; - var pageId = Number($attrs.pageId); - var isEdit = pageId !== 0; - var autosaveFrequency = 30; // AutoSave interval in seconds. - var isMarkdown = $attrs.editorType === 'markdown'; + let pageId = Number($attrs.pageId); + let isEdit = pageId !== 0; + let autosaveFrequency = 30; // AutoSave interval in seconds. + let isMarkdown = $attrs.editorType === 'markdown'; $scope.draftsEnabled = $attrs.draftsEnabled === 'true'; $scope.isUpdateDraft = Number($attrs.pageUpdateDraft) === 1; $scope.isNewPageDraft = Number($attrs.pageNewDraft) === 1; // Set initial header draft text if ($scope.isUpdateDraft || $scope.isNewPageDraft) { - $scope.draftText = 'Editing Draft' + $scope.draftText = trans('entities.pages_editing_draft'); } else { - $scope.draftText = 'Editing Page' + $scope.draftText = trans('entities.pages_editing_page'); } - var autoSave = false; + let autoSave = false; - var currentContent = { + let currentContent = { title: false, html: false }; @@ -351,8 +352,8 @@ export default function (ngApp, events) { autoSave = $interval(() => { // Return if manually saved recently to prevent bombarding the server if (Date.now() - lastSave < (1000*autosaveFrequency)/2) return; - var newTitle = $('#name').val(); - var newHtml = $scope.editContent; + let newTitle = $('#name').val(); + let newHtml = $scope.editContent; if (newTitle !== currentContent.title || newHtml !== currentContent.html) { currentContent.html = newHtml; @@ -369,7 +370,7 @@ export default function (ngApp, events) { */ function saveDraft() { if (!$scope.draftsEnabled) return; - var data = { + let data = { name: $('#name').val(), html: isMarkdown ? $sce.getTrustedHtml($scope.displayContent) : $scope.editContent }; @@ -379,14 +380,14 @@ export default function (ngApp, events) { let url = window.baseUrl('/ajax/page/' + pageId + '/save-draft'); $http.put(url, data).then(responseData => { draftErroring = false; - var updateTime = moment.utc(moment.unix(responseData.data.timestamp)).toDate(); + let updateTime = moment.utc(moment.unix(responseData.data.timestamp)).toDate(); $scope.draftText = responseData.data.message + moment(updateTime).format('HH:mm'); if (!$scope.isNewPageDraft) $scope.isUpdateDraft = true; showDraftSaveNotification(); lastSave = Date.now(); }, errorRes => { if (draftErroring) return; - events.emit('error', 'Failed to save draft. Ensure you have internet connection before saving this page.') + events.emit('error', trans('errors.page_draft_autosave_fail')); draftErroring = true; }); } @@ -419,7 +420,7 @@ export default function (ngApp, events) { let url = window.baseUrl('/ajax/page/' + pageId); $http.get(url).then((responseData) => { if (autoSave) $interval.cancel(autoSave); - $scope.draftText = 'Editing Page'; + $scope.draftText = trans('entities.pages_editing_page'); $scope.isUpdateDraft = false; $scope.$broadcast('html-update', responseData.data.html); $scope.$broadcast('markdown-update', responseData.data.markdown || responseData.data.html); @@ -427,7 +428,7 @@ export default function (ngApp, events) { $timeout(() => { startAutoSave(); }, 1000); - events.emit('success', 'Draft discarded, The editor has been updated with the current page content'); + events.emit('success', trans('entities.pages_draft_discarded')); }); }; @@ -505,20 +506,6 @@ export default function (ngApp, events) { } }; - /** - * Save the tags to the current page. - */ - $scope.saveTags = function() { - setTagOrder(); - let postData = {tags: $scope.tags}; - let url = window.baseUrl('/ajax/tags/update/page/' + pageId); - $http.post(url, postData).then((responseData) => { - $scope.tags = responseData.data.tags; - addEmptyTag(); - events.emit('success', responseData.data.message); - }) - }; - /** * Remove a tag from the current list. * @param tag @@ -588,7 +575,7 @@ export default function (ngApp, events) { * Get files for the current page from the server. */ function getFiles() { - let url = window.baseUrl(`/attachments/get/page/${pageId}`) + let url = window.baseUrl(`/attachments/get/page/${pageId}`); $http.get(url).then(resp => { $scope.files = resp.data; currentOrder = resp.data.map(file => {return file.id}).join(':'); @@ -606,7 +593,7 @@ export default function (ngApp, events) { $scope.$apply(() => { $scope.files.push(data); }); - events.emit('success', 'File uploaded'); + events.emit('success', trans('entities.attachments_file_uploaded')); }; /** @@ -624,7 +611,7 @@ export default function (ngApp, events) { data.link = ''; } }); - events.emit('success', 'File updated'); + events.emit('success', trans('entities.attachments_file_updated')); }; /** @@ -650,7 +637,7 @@ export default function (ngApp, events) { file.uploaded_to = pageId; $http.post(window.baseUrl('/attachments/link'), file).then(resp => { $scope.files.push(resp.data); - events.emit('success', 'Link attached'); + events.emit('success', trans('entities.attachments_link_attached')); $scope.file = getCleanFile(); }, checkError('link')); }; @@ -684,7 +671,7 @@ export default function (ngApp, events) { $scope.editFile.link = ''; } $scope.editFile = false; - events.emit('success', 'Attachment details updated'); + events.emit('success', trans('entities.attachments_updated_success')); }, checkError('edit')); }; diff --git a/resources/assets/js/directives.js b/resources/assets/js/directives.js index 44d1a14e1..ef8bcd85c 100644 --- a/resources/assets/js/directives.js +++ b/resources/assets/js/directives.js @@ -1,38 +1,8 @@ "use strict"; -const DropZone = require('dropzone'); -const markdown = require('marked'); +import DropZone from "dropzone"; +import markdown from "marked"; -module.exports = function (ngApp, events) { - - /** - * Toggle Switches - * Has basic on/off functionality. - * Use string values of 'true' & 'false' to dictate the current state. - */ - ngApp.directive('toggleSwitch', function () { - return { - restrict: 'A', - template: ` -
- -
-
- `, - scope: true, - link: function (scope, element, attrs) { - scope.name = attrs.name; - scope.value = attrs.value; - scope.isActive = scope.value == true && scope.value != 'false'; - scope.value = (scope.value == true && scope.value != 'false') ? 'true' : 'false'; - - scope.switch = function () { - scope.isActive = !scope.isActive; - scope.value = scope.isActive ? 'true' : 'false'; - } - - } - }; - }); +export default function (ngApp, events) { /** * Common tab controls using simple jQuery functions. @@ -65,7 +35,7 @@ module.exports = function (ngApp, events) { }); /** - * Sub form component to allow inner-form sections to act like thier own forms. + * Sub form component to allow inner-form sections to act like their own forms. */ ngApp.directive('subForm', function() { return { @@ -80,96 +50,13 @@ module.exports = function (ngApp, events) { element.find('button[type="submit"]').click(submitEvent); function submitEvent(e) { - e.preventDefault() + e.preventDefault(); if (attrs.subForm) scope.$eval(attrs.subForm); } } }; }); - - /** - * Image Picker - * Is a simple front-end interface that connects to an ImageManager if present. - */ - ngApp.directive('imagePicker', ['$http', 'imageManagerService', function ($http, imageManagerService) { - return { - restrict: 'E', - template: ` -
-
- Image Preview - Image Preview -
- -
- - - | - - - -
- `, - scope: { - name: '@', - resizeHeight: '@', - resizeWidth: '@', - resizeCrop: '@', - showRemove: '=', - currentImage: '@', - currentId: '@', - defaultImage: '@', - imageClass: '@' - }, - link: function (scope, element, attrs) { - let usingIds = typeof scope.currentId !== 'undefined' || scope.currentId === 'false'; - scope.image = scope.currentImage; - scope.value = scope.currentImage || ''; - if (usingIds) scope.value = scope.currentId; - - function setImage(imageModel, imageUrl) { - scope.image = imageUrl; - scope.value = usingIds ? imageModel.id : imageUrl; - } - - scope.reset = function () { - setImage({id: 0}, scope.defaultImage); - }; - - scope.remove = function () { - scope.image = 'none'; - scope.value = 'none'; - }; - - scope.showImageManager = function () { - imageManagerService.show((image) => { - scope.updateImageFromModel(image); - }); - }; - - scope.updateImageFromModel = function (model) { - let isResized = scope.resizeWidth && scope.resizeHeight; - - if (!isResized) { - scope.$apply(() => { - setImage(model, model.url); - }); - return; - } - - let cropped = scope.resizeCrop ? 'true' : 'false'; - let requestString = '/images/thumb/' + model.id + '/' + scope.resizeWidth + '/' + scope.resizeHeight + '/' + cropped; - requestString = window.baseUrl(requestString); - $http.get(requestString).then((response) => { - setImage(model, response.data.url); - }); - }; - - } - }; - }]); - /** * DropZone * Used for uploading images @@ -179,25 +66,26 @@ module.exports = function (ngApp, events) { restrict: 'E', template: `
-
Drop files or click here to upload
+
{{message}}
`, scope: { uploadUrl: '@', eventSuccess: '=', eventError: '=', - uploadedTo: '@' + uploadedTo: '@', }, link: function (scope, element, attrs) { + scope.message = attrs.message; if (attrs.placeholder) element[0].querySelector('.dz-message').textContent = attrs.placeholder; - var dropZone = new DropZone(element[0].querySelector('.dropzone-container'), { + let dropZone = new DropZone(element[0].querySelector('.dropzone-container'), { url: scope.uploadUrl, init: function () { - var dz = this; + let dz = this; dz.on('sending', function (file, xhr, data) { - var token = window.document.querySelector('meta[name=token]').getAttribute('content'); + let token = window.document.querySelector('meta[name=token]').getAttribute('content'); data.append('_token', token); - var uploadedTo = typeof scope.uploadedTo === 'undefined' ? 0 : scope.uploadedTo; + let uploadedTo = typeof scope.uploadedTo === 'undefined' ? 0 : scope.uploadedTo; data.append('uploaded_to', uploadedTo); }); if (typeof scope.eventSuccess !== 'undefined') dz.on('success', scope.eventSuccess); @@ -214,7 +102,7 @@ module.exports = function (ngApp, events) { $(file.previewElement).find('[data-dz-errormessage]').text(message); } - if (xhr.status === 413) setMessage('The server does not allow uploads of this size. Please try a smaller file.'); + if (xhr.status === 413) setMessage(trans('errors.server_upload_limit')); if (errorMessage.file) setMessage(errorMessage.file[0]); }); @@ -273,7 +161,7 @@ module.exports = function (ngApp, events) { function tinyMceSetup(editor) { editor.on('ExecCommand change NodeChange ObjectResized', (e) => { - var content = editor.getContent(); + let content = editor.getContent(); $timeout(() => { scope.mceModel = content; }); @@ -301,9 +189,9 @@ module.exports = function (ngApp, events) { // Custom tinyMCE plugins tinymce.PluginManager.add('customhr', function (editor) { editor.addCommand('InsertHorizontalRule', function () { - var hrElem = document.createElement('hr'); - var cNode = editor.selection.getNode(); - var parentNode = cNode.parentNode; + let hrElem = document.createElement('hr'); + let cNode = editor.selection.getNode(); + let parentNode = cNode.parentNode; parentNode.insertBefore(hrElem, cNode); }); @@ -373,15 +261,21 @@ module.exports = function (ngApp, events) { link: function (scope, element, attrs) { // Elements - const input = element.find('[markdown-input] textarea').first(); - const display = element.find('.markdown-display').first(); - const insertImage = element.find('button[data-action="insertImage"]'); - const insertEntityLink = element.find('button[data-action="insertEntityLink"]') + const $input = element.find('[markdown-input] textarea').first(); + const $display = element.find('.markdown-display').first(); + const $insertImage = element.find('button[data-action="insertImage"]'); + const $insertEntityLink = element.find('button[data-action="insertEntityLink"]'); + + // Prevent markdown display link click redirect + $display.on('click', 'a', function(event) { + event.preventDefault(); + window.open(this.getAttribute('href')); + }); let currentCaretPos = 0; - input.blur(event => { - currentCaretPos = input[0].selectionStart; + $input.blur(event => { + currentCaretPos = $input[0].selectionStart; }); // Scroll sync @@ -391,10 +285,10 @@ module.exports = function (ngApp, events) { displayHeight; function setScrollHeights() { - inputScrollHeight = input[0].scrollHeight; - inputHeight = input.height(); - displayScrollHeight = display[0].scrollHeight; - displayHeight = display.height(); + inputScrollHeight = $input[0].scrollHeight; + inputHeight = $input.height(); + displayScrollHeight = $display[0].scrollHeight; + displayHeight = $display.height(); } setTimeout(() => { @@ -403,29 +297,29 @@ module.exports = function (ngApp, events) { window.addEventListener('resize', setScrollHeights); let scrollDebounceTime = 800; let lastScroll = 0; - input.on('scroll', event => { + $input.on('scroll', event => { let now = Date.now(); if (now - lastScroll > scrollDebounceTime) { setScrollHeights() } - let scrollPercent = (input.scrollTop() / (inputScrollHeight - inputHeight)); + let scrollPercent = ($input.scrollTop() / (inputScrollHeight - inputHeight)); let displayScrollY = (displayScrollHeight - displayHeight) * scrollPercent; - display.scrollTop(displayScrollY); + $display.scrollTop(displayScrollY); lastScroll = now; }); // Editor key-presses - input.keydown(event => { + $input.keydown(event => { // Insert image shortcut if (event.which === 73 && event.ctrlKey && event.shiftKey) { event.preventDefault(); - let caretPos = input[0].selectionStart; - let currentContent = input.val(); + let caretPos = $input[0].selectionStart; + let currentContent = $input.val(); const mdImageText = "![](http://)"; - input.val(currentContent.substring(0, caretPos) + mdImageText + currentContent.substring(caretPos)); - input.focus(); - input[0].selectionStart = caretPos + ("![](".length); - input[0].selectionEnd = caretPos + ('![](http://'.length); + $input.val(currentContent.substring(0, caretPos) + mdImageText + currentContent.substring(caretPos)); + $input.focus(); + $input[0].selectionStart = caretPos + ("![](".length); + $input[0].selectionEnd = caretPos + ('![](http://'.length); return; } @@ -440,48 +334,48 @@ module.exports = function (ngApp, events) { }); // Insert image from image manager - insertImage.click(event => { + $insertImage.click(event => { window.ImageManager.showExternal(image => { let caretPos = currentCaretPos; - let currentContent = input.val(); + let currentContent = $input.val(); let mdImageText = "![" + image.name + "](" + image.thumbs.display + ")"; - input.val(currentContent.substring(0, caretPos) + mdImageText + currentContent.substring(caretPos)); - input.change(); + $input.val(currentContent.substring(0, caretPos) + mdImageText + currentContent.substring(caretPos)); + $input.change(); }); }); function showLinkSelector() { window.showEntityLinkSelector((entity) => { let selectionStart = currentCaretPos; - let selectionEnd = input[0].selectionEnd; + let selectionEnd = $input[0].selectionEnd; let textSelected = (selectionEnd !== selectionStart); - let currentContent = input.val(); + let currentContent = $input.val(); if (textSelected) { let selectedText = currentContent.substring(selectionStart, selectionEnd); let linkText = `[${selectedText}](${entity.link})`; - input.val(currentContent.substring(0, selectionStart) + linkText + currentContent.substring(selectionEnd)); + $input.val(currentContent.substring(0, selectionStart) + linkText + currentContent.substring(selectionEnd)); } else { let linkText = ` [${entity.name}](${entity.link}) `; - input.val(currentContent.substring(0, selectionStart) + linkText + currentContent.substring(selectionStart)) + $input.val(currentContent.substring(0, selectionStart) + linkText + currentContent.substring(selectionStart)) } - input.change(); + $input.change(); }); } - insertEntityLink.click(showLinkSelector); + $insertEntityLink.click(showLinkSelector); // Upload and insert image on paste function editorPaste(e) { e = e.originalEvent; if (!e.clipboardData) return - var items = e.clipboardData.items; + let items = e.clipboardData.items; if (!items) return; - for (var i = 0; i < items.length; i++) { + for (let i = 0; i < items.length; i++) { uploadImage(items[i].getAsFile()); } } - input.on('paste', editorPaste); + $input.on('paste', editorPaste); // Handle image drop, Uploads images to BookStack. function handleImageDrop(event) { @@ -493,17 +387,17 @@ module.exports = function (ngApp, events) { } } - input.on('drop', handleImageDrop); + $input.on('drop', handleImageDrop); // Handle image upload and add image into markdown content function uploadImage(file) { if (file.type.indexOf('image') !== 0) return; - var formData = new FormData(); - var ext = 'png'; - var xhr = new XMLHttpRequest(); + let formData = new FormData(); + let ext = 'png'; + let xhr = new XMLHttpRequest(); if (file.name) { - var fileNameMatches = file.name.match(/\.(.+)$/); + let fileNameMatches = file.name.match(/\.(.+)$/); if (fileNameMatches) { ext = fileNameMatches[1]; } @@ -511,17 +405,17 @@ module.exports = function (ngApp, events) { // Insert image into markdown let id = "image-" + Math.random().toString(16).slice(2); - let selectStart = input[0].selectionStart; - let selectEnd = input[0].selectionEnd; - let content = input[0].value; + let selectStart = $input[0].selectionStart; + let selectEnd = $input[0].selectionEnd; + let content = $input[0].value; let selectText = content.substring(selectStart, selectEnd); let placeholderImage = window.baseUrl(`/loading.gif#upload${id}`); let innerContent = ((selectEnd > selectStart) ? `![${selectText}]` : '![]') + `(${placeholderImage})`; - input[0].value = content.substring(0, selectStart) + innerContent + content.substring(selectEnd); + $input[0].value = content.substring(0, selectStart) + innerContent + content.substring(selectEnd); - input.focus(); - input[0].selectionStart = selectStart; - input[0].selectionEnd = selectStart; + $input.focus(); + $input[0].selectionStart = selectStart; + $input[0].selectionEnd = selectStart; let remoteFilename = "image-" + Date.now() + "." + ext; formData.append('file', file, remoteFilename); @@ -529,20 +423,20 @@ module.exports = function (ngApp, events) { xhr.open('POST', window.baseUrl('/images/gallery/upload')); xhr.onload = function () { - let selectStart = input[0].selectionStart; + let selectStart = $input[0].selectionStart; if (xhr.status === 200 || xhr.status === 201) { - var result = JSON.parse(xhr.responseText); - input[0].value = input[0].value.replace(placeholderImage, result.thumbs.display); - input.change(); + let result = JSON.parse(xhr.responseText); + $input[0].value = $input[0].value.replace(placeholderImage, result.thumbs.display); + $input.change(); } else { - console.log('An error occurred uploading the image'); + console.log(trans('errors.image_upload_error')); console.log(xhr.responseText); - input[0].value = input[0].value.replace(innerContent, ''); - input.change(); + $input[0].value = $input[0].value.replace(innerContent, ''); + $input.change(); } - input.focus(); - input[0].selectionStart = selectStart; - input[0].selectionEnd = selectStart; + $input.focus(); + $input[0].selectionStart = selectStart; + $input[0].selectionEnd = selectStart; }; xhr.send(formData); } @@ -680,8 +574,7 @@ module.exports = function (ngApp, events) { } // Enter or tab key else if ((event.keyCode === 13 || event.keyCode === 9) && !event.shiftKey) { - let text = suggestionElems[active].textContent; - currentInput[0].value = text; + currentInput[0].value = suggestionElems[active].textContent; currentInput.focus(); $suggestionBox.hide(); isShowing = false; @@ -732,14 +625,13 @@ module.exports = function (ngApp, events) { // Build suggestions $suggestionBox[0].innerHTML = ''; for (let i = 0; i < suggestions.length; i++) { - var suggestion = document.createElement('li'); + let suggestion = document.createElement('li'); suggestion.textContent = suggestions[i]; suggestion.onclick = suggestionClick; if (i === 0) { - suggestion.className = 'active' + suggestion.className = 'active'; active = 0; } - ; $suggestionBox[0].appendChild(suggestion); } @@ -748,12 +640,11 @@ module.exports = function (ngApp, events) { // Suggestion click event function suggestionClick(event) { - let text = this.textContent; - currentInput[0].value = text; + currentInput[0].value = this.textContent; currentInput.focus(); $suggestionBox.hide(); isShowing = false; - }; + } // Get suggestions & cache function getSuggestions(input, url) { @@ -779,7 +670,7 @@ module.exports = function (ngApp, events) { ngApp.directive('entityLinkSelector', [function($http) { return { - restict: 'A', + restrict: 'A', link: function(scope, element, attrs) { const selectButton = element.find('.entity-link-selector-confirm'); @@ -843,7 +734,7 @@ module.exports = function (ngApp, events) { const input = element.find('[entity-selector-input]').first(); // Detect double click events - var lastClick = 0; + let lastClick = 0; function isDoubleClick() { let now = Date.now(); let answer = now - lastClick < 300; diff --git a/resources/assets/js/global.js b/resources/assets/js/global.js index 9aa5dff52..650919f85 100644 --- a/resources/assets/js/global.js +++ b/resources/assets/js/global.js @@ -1,11 +1,11 @@ "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); - 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(); - }); - 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'); - } - +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(() => { + 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); +}); + +// 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"; diff --git a/resources/assets/js/pages/page-form.js b/resources/assets/js/pages/page-form.js index 1fb8b915f..0f44b3d09 100644 --- a/resources/assets/js/pages/page-form.js +++ b/resources/assets/js/pages/page-form.js @@ -60,108 +60,108 @@ function registerEditorShortcuts(editor) { editor.addShortcut('meta+shift+E', '', ['FormatBlock', false, 'code']); } -var mceOptions = module.exports = { - selector: '#html-editor', - content_css: [ - window.baseUrl('/css/styles.css'), - window.baseUrl('/libs/material-design-iconic-font/css/material-design-iconic-font.min.css') - ], - body_class: 'page-content', - relative_urls: false, - remove_script_host: false, - document_base_url: window.baseUrl('/'), - statusbar: false, - menubar: false, - paste_data_images: false, - extended_valid_elements: 'pre[*]', - automatic_uploads: false, - valid_children: "-div[p|pre|h1|h2|h3|h4|h5|h6|blockquote]", - plugins: "image table textcolor paste link fullscreen imagetools code customhr autosave lists", - imagetools_toolbar: 'imageoptions', - toolbar: "undo redo | styleselect | bold italic underline strikethrough superscript subscript | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | table image-insert link hr | removeformat code fullscreen", - content_style: "body {padding-left: 15px !important; padding-right: 15px !important; margin:0!important; margin-left:auto!important;margin-right:auto!important;}", - style_formats: [ - {title: "Header Large", format: "h2"}, - {title: "Header Medium", format: "h3"}, - {title: "Header Small", format: "h4"}, - {title: "Header Tiny", format: "h5"}, - {title: "Paragraph", format: "p", exact: true, classes: ''}, - {title: "Blockquote", format: "blockquote"}, - {title: "Code Block", icon: "code", format: "pre"}, - {title: "Inline Code", icon: "code", inline: "code"}, - {title: "Callouts", items: [ - {title: "Success", block: 'p', exact: true, attributes : {'class' : 'callout success'}}, - {title: "Info", block: 'p', exact: true, attributes : {'class' : 'callout info'}}, - {title: "Warning", block: 'p', exact: true, attributes : {'class' : 'callout warning'}}, - {title: "Danger", block: 'p', exact: true, attributes : {'class' : 'callout danger'}} - ]} - ], - style_formats_merge: false, - formats: { - alignleft: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-left'}, - aligncenter: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-center'}, - alignright: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-right'}, - }, - file_browser_callback: function (field_name, url, type, win) { +export default function() { + let settings = { + selector: '#html-editor', + content_css: [ + window.baseUrl('/css/styles.css'), + window.baseUrl('/libs/material-design-iconic-font/css/material-design-iconic-font.min.css') + ], + body_class: 'page-content', + relative_urls: false, + remove_script_host: false, + document_base_url: window.baseUrl('/'), + statusbar: false, + menubar: false, + paste_data_images: false, + extended_valid_elements: 'pre[*]', + automatic_uploads: false, + valid_children: "-div[p|pre|h1|h2|h3|h4|h5|h6|blockquote]", + plugins: "image table textcolor paste link autolink fullscreen imagetools code customhr autosave lists", + imagetools_toolbar: 'imageoptions', + toolbar: "undo redo | styleselect | bold italic underline strikethrough superscript subscript | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | table image-insert link hr | removeformat code fullscreen", + content_style: "body {padding-left: 15px !important; padding-right: 15px !important; margin:0!important; margin-left:auto!important;margin-right:auto!important;}", + style_formats: [ + {title: "Header Large", format: "h2"}, + {title: "Header Medium", format: "h3"}, + {title: "Header Small", format: "h4"}, + {title: "Header Tiny", format: "h5"}, + {title: "Paragraph", format: "p", exact: true, classes: ''}, + {title: "Blockquote", format: "blockquote"}, + {title: "Code Block", icon: "code", format: "pre"}, + {title: "Inline Code", icon: "code", inline: "code"}, + {title: "Callouts", items: [ + {title: "Success", block: 'p', exact: true, attributes : {'class' : 'callout success'}}, + {title: "Info", block: 'p', exact: true, attributes : {'class' : 'callout info'}}, + {title: "Warning", block: 'p', exact: true, attributes : {'class' : 'callout warning'}}, + {title: "Danger", block: 'p', exact: true, attributes : {'class' : 'callout danger'}} + ]} + ], + style_formats_merge: false, + formats: { + alignleft: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-left'}, + aligncenter: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-center'}, + alignright: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-right'}, + }, + file_browser_callback: function (field_name, url, type, win) { - if (type === 'file') { - window.showEntityLinkSelector(function(entity) { - let originalField = win.document.getElementById(field_name); - originalField.value = entity.link; - $(originalField).closest('.mce-form').find('input').eq(2).val(entity.name); - }); - } + if (type === 'file') { + window.showEntityLinkSelector(function(entity) { + let originalField = win.document.getElementById(field_name); + originalField.value = entity.link; + $(originalField).closest('.mce-form').find('input').eq(2).val(entity.name); + }); + } - if (type === 'image') { - // Show image manager - window.ImageManager.showExternal(function (image) { + if (type === 'image') { + // Show image manager + window.ImageManager.showExternal(function (image) { - // Set popover link input to image url then fire change event - // to ensure the new value sticks - win.document.getElementById(field_name).value = image.url; - if ("createEvent" in document) { - let evt = document.createEvent("HTMLEvents"); - evt.initEvent("change", false, true); - win.document.getElementById(field_name).dispatchEvent(evt); - } else { - win.document.getElementById(field_name).fireEvent("onchange"); - } + // Set popover link input to image url then fire change event + // to ensure the new value sticks + win.document.getElementById(field_name).value = image.url; + if ("createEvent" in document) { + let evt = document.createEvent("HTMLEvents"); + evt.initEvent("change", false, true); + win.document.getElementById(field_name).dispatchEvent(evt); + } else { + win.document.getElementById(field_name).fireEvent("onchange"); + } - // Replace the actively selected content with the linked image - let html = ``; - html += `${image.name}`; - html += ''; - win.tinyMCE.activeEditor.execCommand('mceInsertContent', false, html); - }); - } + // Replace the actively selected content with the linked image + let html = ``; + html += `${image.name}`; + html += ''; + win.tinyMCE.activeEditor.execCommand('mceInsertContent', false, html); + }); + } - }, - paste_preprocess: function (plugin, args) { - let content = args.content; - if (content.indexOf('`; - html += `${image.name}`; - html += ''; - editor.execCommand('mceInsertContent', false, html); - }); - } - }); + // Custom Image picker button + editor.addButton('image-insert', { + title: 'My title', + icon: 'image', + tooltip: 'Insert an image', + onclick: function () { + window.ImageManager.showExternal(function (image) { + let html = ``; + html += `${image.name}`; + html += ''; + editor.execCommand('mceInsertContent', false, html); + }); + } + }); - // Paste image-uploads - editor.on('paste', function(event) { - editorPaste(event, editor); - }); - } -}; \ No newline at end of file + // Paste image-uploads + editor.on('paste', function(event) { + editorPaste(event, editor); + }); + } + }; + return settings; +} \ No newline at end of file diff --git a/resources/assets/js/pages/page-show.js b/resources/assets/js/pages/page-show.js index 41b92453f..0f45e1987 100644 --- a/resources/assets/js/pages/page-show.js +++ b/resources/assets/js/pages/page-show.js @@ -1,16 +1,16 @@ "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 ? '' : ''); + 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)) { diff --git a/resources/assets/js/translations.js b/resources/assets/js/translations.js new file mode 100644 index 000000000..306c696b6 --- /dev/null +++ b/resources/assets/js/translations.js @@ -0,0 +1,47 @@ +/** + * 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 diff --git a/resources/assets/sass/_blocks.scss b/resources/assets/sass/_blocks.scss index 7eb595d36..a2023aa37 100644 --- a/resources/assets/sass/_blocks.scss +++ b/resources/assets/sass/_blocks.scss @@ -136,9 +136,6 @@ background-color: #EEE; padding: $-s; display: block; - > * { - display: inline-block; - } &:before { font-family: 'Material-Design-Iconic-Font'; padding-right: $-s; diff --git a/resources/assets/sass/_buttons.scss b/resources/assets/sass/_buttons.scss index 5de889673..791a5bb72 100644 --- a/resources/assets/sass/_buttons.scss +++ b/resources/assets/sass/_buttons.scss @@ -108,5 +108,4 @@ $button-border-radius: 2px; cursor: default; box-shadow: none; } -} - +} \ No newline at end of file diff --git a/resources/assets/sass/_components.scss b/resources/assets/sass/_components.scss index 2f9051a52..5328057d9 100644 --- a/resources/assets/sass/_components.scss +++ b/resources/assets/sass/_components.scss @@ -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 diff --git a/resources/assets/sass/_forms.scss b/resources/assets/sass/_forms.scss index 4e643dcda..7e6b800d2 100644 --- a/resources/assets/sass/_forms.scss +++ b/resources/assets/sass/_forms.scss @@ -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 diff --git a/resources/assets/sass/_lists.scss b/resources/assets/sass/_lists.scss index e98e5bfcd..6acc47468 100644 --- a/resources/assets/sass/_lists.scss +++ b/resources/assets/sass/_lists.scss @@ -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; } diff --git a/resources/assets/sass/_pages.scss b/resources/assets/sass/_pages.scss index 0052a3319..e5334c69c 100755 --- a/resources/assets/sass/_pages.scss +++ b/resources/assets/sass/_pages.scss @@ -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; diff --git a/resources/assets/sass/_tables.scss b/resources/assets/sass/_tables.scss index 37c61159d..21553b839 100644 --- a/resources/assets/sass/_tables.scss +++ b/resources/assets/sass/_tables.scss @@ -35,6 +35,12 @@ table.table { tr:hover { background-color: #EEE; } + .text-right { + text-align: right; + } + .text-center { + text-align: center; + } } table.no-style { diff --git a/resources/assets/sass/_text.scss b/resources/assets/sass/_text.scss index 9bad2e83d..74eb6875a 100644 --- a/resources/assets/sass/_text.scss +++ b/resources/assets/sass/_text.scss @@ -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 diff --git a/resources/assets/sass/export-styles.scss b/resources/assets/sass/export-styles.scss index 60450f3e2..7e1ab4e9e 100644 --- a/resources/assets/sass/export-styles.scss +++ b/resources/assets/sass/export-styles.scss @@ -1,4 +1,4 @@ -//@import "reset"; +@import "reset"; @import "variables"; @import "mixins"; @import "html"; diff --git a/resources/lang/de/settings.php b/resources/lang/de/settings.php index 183480faa..0017acd1d 100644 --- a/resources/lang/de/settings.php +++ b/resources/lang/de/settings.php @@ -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' => 'Öffentliche Ansicht erlauben?', - 'app_secure_images' => 'Erh&oml;hte Sicherheit für Bilduploads aktivieren?', + 'app_secure_images' => 'Erhöhte Sicherheit für Bilduploads aktivieren?', 'app_secure_images_desc' => 'Aus Leistungsgründen sind alle Bilder öffentlich sichtbar. Diese Option fügt zufä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ählen sie den Editor aus, der von allen Benutzern genutzt werden soll, um Seiten zu editieren.', diff --git a/resources/lang/en/auth.php b/resources/lang/en/auth.php index ffdb1cf45..b734828fc 100644 --- a/resources/lang/en/auth.php +++ b/resources/lang/en/auth.php @@ -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 diff --git a/resources/lang/en/common.php b/resources/lang/en/common.php new file mode 100644 index 000000000..31ef42e97 --- /dev/null +++ b/resources/lang/en/common.php @@ -0,0 +1,58 @@ + '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 diff --git a/resources/lang/en/components.php b/resources/lang/en/components.php new file mode 100644 index 000000000..b9108702a --- /dev/null +++ b/resources/lang/en/components.php @@ -0,0 +1,24 @@ + '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 diff --git a/resources/lang/en/entities.php b/resources/lang/en/entities.php new file mode 100644 index 000000000..109b6ee2a --- /dev/null +++ b/resources/lang/en/entities.php @@ -0,0 +1,226 @@ + 'Recently Created', + 'recently_created_pages' => 'Recently Created Pages', + 'recently_updated_pages' => 'Recently Updated Pages', + 'recently_created_chapters' => 'Recently Created Chapters', + 'recently_created_books' => 'Recently Created Books', + 'recently_update' => 'Recently Updated', + 'recently_viewed' => 'Recently Viewed', + 'recent_activity' => 'Recent Activity', + 'create_now' => 'Create one now', + 'revisions' => 'Revisions', + 'meta_created' => 'Created :timeLength', + 'meta_created_name' => 'Created :timeLength by :user', + 'meta_updated' => 'Updated :timeLength', + 'meta_updated_name' => 'Updated :timeLength by :user', + 'x_pages' => ':count Pages', + 'entity_select' => 'Entity Select', + 'images' => 'Images', + 'my_recent_drafts' => 'My Recent Drafts', + 'my_recently_viewed' => 'My Recently Viewed', + 'no_pages_viewed' => 'You have not viewed any pages', + 'no_pages_recently_created' => 'No pages have been recently created', + 'no_pages_recently_updated' => 'No pages have been recently updated', + + /** + * Permissions and restrictions + */ + 'permissions' => 'Permissions', + 'permissions_intro' => 'Once enabled, These permissions will take priority over any set role permissions.', + 'permissions_enable' => 'Enable Custom Permissions', + 'permissions_save' => 'Save Permissions', + + /** + * Search + */ + 'search_results' => 'Search Results', + 'search_results_page' => 'Page Search Results', + 'search_results_chapter' => 'Chapter Search Results', + 'search_results_book' => 'Book Search Results', + 'search_clear' => 'Clear Search', + 'search_view_pages' => 'View all matches pages', + 'search_view_chapters' => 'View all matches chapters', + 'search_view_books' => 'View all matches books', + 'search_no_pages' => 'No pages matched this search', + 'search_for_term' => 'Search for :term', + 'search_page_for_term' => 'Page search for :term', + 'search_chapter_for_term' => 'Chapter search for :term', + 'search_book_for_term' => 'Books search for :term', + + /** + * Books + */ + 'book' => 'Book', + 'books' => 'Books', + 'books_empty' => 'No books have been created', + 'books_popular' => 'Popular Books', + 'books_recent' => 'Recent Books', + 'books_popular_empty' => 'The most popular books will appear here.', + 'books_create' => 'Create New Book', + 'books_delete' => 'Delete Book', + 'books_delete_named' => 'Delete Book :bookName', + 'books_delete_explain' => 'This will delete the book with the name \':bookName\', All pages and chapters will be removed.', + 'books_delete_confirmation' => 'Are you sure you want to delete this book?', + 'books_edit' => 'Edit Book', + 'books_edit_named' => 'Edit Book :bookName', + 'books_form_book_name' => 'Book Name', + 'books_save' => 'Save Book', + 'books_permissions' => 'Book Permissions', + 'books_permissions_updated' => 'Book Permissions Updated', + 'books_empty_contents' => 'No pages or chapters have been created for this book.', + 'books_empty_create_page' => 'Create a new page', + 'books_empty_or' => 'or', + 'books_empty_sort_current_book' => 'Sort the current book', + 'books_empty_add_chapter' => 'Add a chapter', + 'books_permissions_active' => 'Book Permissions Active', + 'books_search_this' => 'Search this book', + 'books_navigation' => 'Book Navigation', + 'books_sort' => 'Sort Book Contents', + 'books_sort_named' => 'Sort Book :bookName', + 'books_sort_show_other' => 'Show Other Books', + 'books_sort_save' => 'Save New Order', + + /** + * Chapters + */ + 'chapter' => 'Chapter', + 'chapters' => 'Chapters', + 'chapters_popular' => 'Popular Chapters', + 'chapters_new' => 'New Chapter', + 'chapters_create' => 'Create New Chapter', + 'chapters_delete' => 'Delete Chapter', + 'chapters_delete_named' => 'Delete Chapter :chapterName', + 'chapters_delete_explain' => 'This will delete the chapter with the name \':chapterName\', All pages will be removed + and added directly to the parent book.', + 'chapters_delete_confirm' => 'Are you sure you want to delete this chapter?', + 'chapters_edit' => 'Edit Chapter', + 'chapters_edit_named' => 'Edit Chapter :chapterName', + 'chapters_save' => 'Save Chapter', + 'chapters_move' => 'Move Chapter', + 'chapters_move_named' => 'Move Chapter :chapterName', + 'chapter_move_success' => 'Chapter moved to :bookName', + 'chapters_permissions' => 'Chapter Permissions', + 'chapters_empty' => 'No pages are currently in this chapter.', + 'chapters_permissions_active' => 'Chapter Permissions Active', + 'chapters_permissions_success' => 'Chapter Permissions Updated', + + /** + * Pages + */ + 'page' => 'Page', + 'pages' => 'Pages', + 'pages_popular' => 'Popular Pages', + 'pages_new' => 'New Page', + 'pages_attachments' => 'Attachments', + 'pages_navigation' => 'Page Navigation', + 'pages_delete' => 'Delete Page', + 'pages_delete_named' => 'Delete Page :pageName', + 'pages_delete_draft_named' => 'Delete Draft Page :pageName', + 'pages_delete_draft' => 'Delete Draft Page', + 'pages_delete_success' => 'Page deleted', + 'pages_delete_draft_success' => 'Draft page deleted', + 'pages_delete_confirm' => 'Are you sure you want to delete this page?', + 'pages_delete_draft_confirm' => 'Are you sure you want to delete this draft page?', + 'pages_editing_named' => 'Editing Page :pageName', + 'pages_edit_toggle_header' => 'Toggle header', + 'pages_edit_save_draft' => 'Save Draft', + 'pages_edit_draft' => 'Edit Page Draft', + 'pages_editing_draft' => 'Editing Draft', + 'pages_editing_page' => 'Editing Page', + 'pages_edit_draft_save_at' => 'Draft saved at ', + 'pages_edit_delete_draft' => 'Delete Draft', + 'pages_edit_discard_draft' => 'Discard Draft', + 'pages_edit_set_changelog' => 'Set Changelog', + 'pages_edit_enter_changelog_desc' => 'Enter a brief description of the changes you\'ve made', + 'pages_edit_enter_changelog' => 'Enter Changelog', + 'pages_save' => 'Save Page', + 'pages_title' => 'Page Title', + 'pages_name' => 'Page Name', + 'pages_md_editor' => 'Editor', + 'pages_md_preview' => 'Preview', + 'pages_md_insert_image' => 'Insert Image', + 'pages_md_insert_link' => 'Insert Entity Link', + 'pages_not_in_chapter' => 'Page is not in a chapter', + 'pages_move' => 'Move Page', + 'pages_move_success' => 'Page moved to ":parentName"', + 'pages_permissions' => 'Page Permissions', + 'pages_permissions_success' => 'Page permissions updated', + 'pages_revisions' => 'Page Revisions', + 'pages_revisions_named' => 'Page Revisions for :pageName', + 'pages_revision_named' => 'Page Revision for :pageName', + 'pages_revisions_created_by' => 'Created By', + 'pages_revisions_date' => 'Revision Date', + 'pages_revisions_changelog' => 'Changelog', + 'pages_revisions_changes' => 'Changes', + 'pages_revisions_current' => 'Current Version', + 'pages_revisions_preview' => 'Preview', + 'pages_revisions_restore' => 'Restore', + 'pages_revisions_none' => 'This page has no revisions', + 'pages_export' => 'Export', + 'pages_export_html' => 'Contained Web File', + 'pages_export_pdf' => 'PDF File', + 'pages_export_text' => 'Plain Text File', + 'pages_copy_link' => 'Copy Link', + 'pages_permissions_active' => 'Page Permissions Active', + 'pages_initial_revision' => 'Initial publish', + 'pages_initial_name' => 'New Page', + 'pages_editing_draft_notification' => 'You are currently editing a draft that was last saved :timeDiff.', + 'pages_draft_edited_notification' => 'This page has been updated by since that time. It is recommended that you discard this draft.', + 'pages_draft_edit_active' => [ + 'start_a' => ':count users have started editing this page', + 'start_b' => ':userName has started editing this page', + 'time_a' => 'since the pages was last updated', + 'time_b' => 'in the last :minCount minutes', + 'message' => ':start :time. Take care not to overwrite each other\'s updates!', + ], + 'pages_draft_discarded' => 'Draft discarded, The editor has been updated with the current page content', + + /** + * Editor sidebar + */ + 'page_tags' => 'Page Tags', + 'tag' => 'Tag', + 'tags' => '', + 'tag_value' => 'Tag Value (Optional)', + 'tags_explain' => "Add some tags to better categorise your content. \n You can assign a value to a tag for more in-depth organisation.", + 'tags_add' => 'Add another tag', + 'attachments' => 'Attachments', + 'attachments_explain' => 'Upload some files or attach some link to display on your page. These are visible in the page sidebar.', + 'attachments_explain_instant_save' => 'Changes here are saved instantly.', + 'attachments_items' => 'Attached Items', + 'attachments_upload' => 'Upload File', + 'attachments_link' => 'Attach Link', + 'attachments_set_link' => 'Set Link', + 'attachments_delete_confirm' => 'Click delete again to confirm you want to delete this attachment.', + 'attachments_dropzone' => 'Drop files or click here to attach a file', + 'attachments_no_files' => 'No files have been uploaded', + 'attachments_explain_link' => 'You can attach a link if you\'d prefer not to upload a file. This can be a link to another page or a link to a file in the cloud.', + 'attachments_link_name' => 'Link Name', + 'attachment_link' => 'Attachment link', + 'attachments_link_url' => 'Link to file', + 'attachments_link_url_hint' => 'Url of site or file', + 'attach' => 'Attach', + 'attachments_edit_file' => 'Edit File', + 'attachments_edit_file_name' => 'File Name', + 'attachments_edit_drop_upload' => 'Drop files or click here to upload and overwrite', + 'attachments_order_updated' => 'Attachment order updated', + 'attachments_updated_success' => 'Attachment details updated', + 'attachments_deleted' => 'Attachment deleted', + 'attachments_file_uploaded' => 'File successfully uploaded', + 'attachments_file_updated' => 'File successfully updated', + 'attachments_link_attached' => 'Link successfully attached to page', + + /** + * Profile View + */ + 'profile_user_for_x' => 'User for :time', + 'profile_created_content' => 'Created Content', + 'profile_not_created_pages' => ':userName has not created any pages', + 'profile_not_created_chapters' => ':userName has not created any chapters', + 'profile_not_created_books' => ':userName has not created any books', +]; \ No newline at end of file diff --git a/resources/lang/en/errors.php b/resources/lang/en/errors.php index b1a252bf3..c4578a37a 100644 --- a/resources/lang/en/errors.php +++ b/resources/lang/en/errors.php @@ -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 diff --git a/resources/lang/en/settings.php b/resources/lang/en/settings.php index 1b0bcad33..ed8a0db43 100644 --- a/resources/lang/en/settings.php +++ b/resources/lang/en/settings.php @@ -1,16 +1,21 @@ '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.
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.
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' + ] + /////////////////////////////////// +]; diff --git a/resources/lang/en/validation.php b/resources/lang/en/validation.php index 20acc9a68..b75af7485 100644 --- a/resources/lang/en/validation.php +++ b/resources/lang/en/validation.php @@ -87,8 +87,8 @@ return [ */ 'custom' => [ - 'attribute-name' => [ - 'rule-name' => 'custom-message', + 'password-confirm' => [ + 'required_with' => 'Password confirmation required', ], ], diff --git a/resources/lang/fr/activities.php b/resources/lang/fr/activities.php new file mode 100644 index 000000000..32f225d5d --- /dev/null +++ b/resources/lang/fr/activities.php @@ -0,0 +1,40 @@ + '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', + +]; diff --git a/resources/lang/fr/auth.php b/resources/lang/fr/auth.php new file mode 100644 index 000000000..41d051c5f --- /dev/null +++ b/resources/lang/fr/auth.php @@ -0,0 +1,74 @@ + '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', +]; diff --git a/resources/lang/fr/common.php b/resources/lang/fr/common.php new file mode 100644 index 000000000..5eb4b8fa8 --- /dev/null +++ b/resources/lang/fr/common.php @@ -0,0 +1,58 @@ + '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', +]; diff --git a/resources/lang/fr/components.php b/resources/lang/fr/components.php new file mode 100644 index 000000000..7c9c4cfc0 --- /dev/null +++ b/resources/lang/fr/components.php @@ -0,0 +1,24 @@ + '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' +]; diff --git a/resources/lang/fr/entities.php b/resources/lang/fr/entities.php new file mode 100644 index 000000000..941259f80 --- /dev/null +++ b/resources/lang/fr/entities.php @@ -0,0 +1,225 @@ + 'Créé rĂ©cemment', + 'recently_created_pages' => 'Pages créées rĂ©cemment', + 'recently_updated_pages' => 'Pages mises Ă  jour rĂ©cemment', + 'recently_created_chapters' => 'Chapitres créés rĂ©cemment', + 'recently_created_books' => 'Livres créés rĂ©cemment', + 'recently_update' => 'Mis Ă  jour rĂ©cemment', + 'recently_viewed' => 'Vus rĂ©cemment', + 'recent_activity' => 'ActivitĂ© rĂ©cente', + 'create_now' => 'En crĂ©er un rĂ©cemment', + 'revisions' => 'RĂ©visions', + 'meta_created' => 'Créé :timeLength', + 'meta_created_name' => 'Créé :timeLength par :user', + 'meta_updated' => 'Mis Ă  jour :timeLength', + 'meta_updated_name' => 'Mis Ă  jour :timeLength par :user', + 'x_pages' => ':count pages', + 'entity_select' => 'SĂ©lectionner l\'entitĂ©', + 'images' => 'Images', + 'my_recent_drafts' => 'Mes brouillons rĂ©cents', + 'my_recently_viewed' => 'Vus rĂ©cemment', + 'no_pages_viewed' => 'Vous n\'avez rien visitĂ© rĂ©cemment', + 'no_pages_recently_created' => 'Aucune page créée rĂ©cemment', + 'no_pages_recently_updated' => 'Aucune page mise Ă  jour rĂ©cemment', + + /** + * Permissions and restrictions + */ + 'permissions' => 'Permissions', + 'permissions_intro' => 'Une fois activĂ©es ces permission prendont la prioritĂ© sur tous les sets de permissions prĂ©-existants.', + 'permissions_enable' => 'Activer les permissions personnalisĂ©es', + 'permissions_save' => 'Enregistrer les permissions', + + /** + * Search + */ + 'search_results' => 'RĂ©sultats de recherche', + 'search_results_page' => 'RĂ©sultats de recherche des pages', + 'search_results_chapter' => 'RĂ©sultats de recherche des chapitres', + 'search_results_book' => 'RĂ©sultats de recherche des livres', + 'search_clear' => 'RĂ©initialiser la recherche', + 'search_view_pages' => 'Voir toutes les pages correspondantes', + 'search_view_chapters' => 'Voir tous les chapitres correspondants', + 'search_view_books' => 'Voir tous les livres correspondants', + 'search_no_pages' => 'Aucune page correspondant Ă  cette recherche', + 'search_for_term' => 'recherche pour :term', + 'search_page_for_term' => 'Recherche de page pour :term', + 'search_chapter_for_term' => 'Recherche de chapitre pour :term', + 'search_book_for_term' => 'Recherche de livres pour :term', + + /** + * Books + */ + 'book' => 'Livre', + 'books' => 'Livres', + 'books_empty' => 'Aucun livre n\'a Ă©tĂ© créé', + 'books_popular' => 'Livres populaires', + 'books_recent' => 'Livres rĂ©cents', + 'books_popular_empty' => 'Les livres les plus populaires apparaĂ®tront ici.', + 'books_create' => 'CrĂ©er un nouveau livre', + 'books_delete' => 'Supprimer un livre', + 'books_delete_named' => 'Supprimer le livre :bookName', + 'books_delete_explain' => 'Ceci va supprimer le livre nommĂ© \':bookName\', Tous les chapitres et pages seront supprimĂ©s.', + 'books_delete_confirmation' => 'ĂŠtes-vous sĂ»r(e) de vouloir supprimer ce livre?', + 'books_edit' => 'Modifier le livre', + 'books_edit_named' => 'Modifier le livre :bookName', + 'books_form_book_name' => 'Nom du livre', + 'books_save' => 'Enregistrer le livre', + 'books_permissions' => 'Permissions du livre', + 'books_permissions_updated' => 'Permissions du livre mises Ă  jour', + 'books_empty_contents' => 'Aucune page ou chapitre n\'a Ă©tĂ© ajoutĂ© Ă  ce livre.', + 'books_empty_create_page' => 'CrĂ©er une nouvelle page', + 'books_empty_or' => 'ou', + 'books_empty_sort_current_book' => 'Trier les pages du livre', + 'books_empty_add_chapter' => 'Ajouter un chapitre', + 'books_permissions_active' => 'Permissions personnalisĂ©es activĂ©es', + 'books_search_this' => 'Chercher dans le livre', + 'books_navigation' => 'Navigation dans le livre', + 'books_sort' => 'Trier les contenus du livre', + 'books_sort_named' => 'Trier le livre :bookName', + 'books_sort_show_other' => 'Afficher d\'autres livres', + 'books_sort_save' => 'Enregistrer l\'ordre', + + /** + * Chapters + */ + 'chapter' => 'Chapitre', + 'chapters' => 'Chapitres', + 'chapters_popular' => 'Chapitres populaires', + 'chapters_new' => 'Nouveau chapitre', + 'chapters_create' => 'CrĂ©er un nouveau chapitre', + 'chapters_delete' => 'Supprimer le chapitre', + 'chapters_delete_named' => 'Supprimer le chapitre :chapterName', + 'chapters_delete_explain' => 'Ceci va supprimer le chapitre \':chapterName\', Toutes les pages seront dĂ©placĂ©e dans le livre parent.', + 'chapters_delete_confirm' => 'Etes-vous sĂ»r(e) de vouloir supprimer ce chapitre?', + 'chapters_edit' => 'Modifier le chapitre', + 'chapters_edit_named' => 'Modifier le chapitre :chapterName', + 'chapters_save' => 'Enregistrer le chapitre', + 'chapters_move' => 'DĂ©place le chapitre', + 'chapters_move_named' => 'DĂ©placer le chapitre :chapterName', + 'chapter_move_success' => 'Chapitre dĂ©placĂ© dans :bookName', + 'chapters_permissions' => 'Permissions du chapitre', + 'chapters_empty' => 'Il n\'y a pas de pages dans ce chapitre actuellement.', + 'chapters_permissions_active' => 'Permissions du chapitre activĂ©es', + 'chapters_permissions_success' => 'Permissions du chapitres mises Ă  jour', + + /** + * Pages + */ + 'page' => 'Page', + 'pages' => 'Pages', + 'pages_popular' => 'Pages populaires', + 'pages_new' => 'Nouvelle page', + 'pages_attachments' => 'Fichiers joints', + 'pages_navigation' => 'Navigation des pages', + 'pages_delete' => 'Supprimer la page', + 'pages_delete_named' => 'Supprimer la page :pageName', + 'pages_delete_draft_named' => 'supprimer le brouillon de la page :pageName', + 'pages_delete_draft' => 'Supprimer le brouillon', + 'pages_delete_success' => 'Page supprimĂ©e', + 'pages_delete_draft_success' => 'Brouillon supprimĂ©', + 'pages_delete_confirm' => 'ĂŠtes-vous sĂ»r(e) de vouloir supprimer cette page?', + 'pages_delete_draft_confirm' => 'ĂŠtes-vous sĂ»r(e) de vouloir supprimer ce brouillon?', + 'pages_editing_named' => 'Modification de la page :pageName', + 'pages_edit_toggle_header' => 'Afficher/cacher l\'en-tĂŞte', + 'pages_edit_save_draft' => 'Enregistrer le brouillon', + 'pages_edit_draft' => 'Modifier le brouillon', + 'pages_editing_draft' => 'Modification du brouillon', + 'pages_editing_page' => 'Modification de la page', + 'pages_edit_draft_save_at' => 'Brouillon sauvĂ© le ', + 'pages_edit_delete_draft' => 'Supprimer le brouillon', + 'pages_edit_discard_draft' => 'Ecarter le brouillon', + 'pages_edit_set_changelog' => 'Remplir le journal des changements', + 'pages_edit_enter_changelog_desc' => 'Entrez une brève description des changements effectuĂ©s', + 'pages_edit_enter_changelog' => 'Entrez dans le journal des changements', + 'pages_save' => 'Enregistrez la page', + 'pages_title' => 'Titre de la page', + 'pages_name' => 'Nom de la page', + 'pages_md_editor' => 'Editeur', + 'pages_md_preview' => 'PrĂ©visualisation', + 'pages_md_insert_image' => 'InsĂ©rer une image', + 'pages_md_insert_link' => 'InsĂ©rer un lien', + 'pages_not_in_chapter' => 'La page n\'est pas dans un chanpitre', + 'pages_move' => 'DĂ©placer la page', + 'pages_move_success' => 'Page dĂ©placĂ©e Ă  ":parentName"', + 'pages_permissions' => 'Permissions de la page', + 'pages_permissions_success' => 'Permissions de la page mises Ă  jour', + 'pages_revisions' => 'RĂ©visions de la page', + 'pages_revisions_named' => 'RĂ©visions pour :pageName', + 'pages_revision_named' => 'RĂ©vision pour :pageName', + 'pages_revisions_created_by' => 'Créé par', + 'pages_revisions_date' => 'Date de rĂ©vision', + 'pages_revisions_changelog' => 'Journal des changements', + 'pages_revisions_changes' => 'Changements', + 'pages_revisions_current' => 'Version courante', + 'pages_revisions_preview' => 'PrĂ©visualisation', + 'pages_revisions_restore' => 'Restaurer', + 'pages_revisions_none' => 'Cette page n\'a aucune rĂ©vision', + 'pages_export' => 'Exporter', + 'pages_export_html' => 'Fichiers web', + 'pages_export_pdf' => 'Fichier PDF', + 'pages_export_text' => 'Document texte', + 'pages_copy_link' => 'Copier le lien', + 'pages_permissions_active' => 'Permissions de page actives', + 'pages_initial_revision' => 'Publication initiale', + 'pages_initial_name' => 'Nouvelle page', + 'pages_editing_draft_notification' => 'Vous Ă©ditez actuellement un brouillon qui a Ă©tĂ© sauvĂ© :timeDiff.', + 'pages_draft_edited_notification' => 'La page a Ă©tĂ© mise Ă  jour depuis votre dernière visit. Vous devriez Ă©carter ce brouillon.', + 'pages_draft_edit_active' => [ + 'start_a' => ':count utilisateurs ont commencĂ© a Ă©diter cette page', + 'start_b' => ':userName a commencĂ© Ă  Ă©diter cette page', + 'time_a' => 'depuis la dernière sauvegarde', + 'time_b' => 'dans les :minCount dernières minutes', + 'message' => ':start :time. Attention a ne pas Ă©craser les mises Ă  jour de quelqu\'un d\'autre!', + ], + 'pages_draft_discarded' => 'Brouuillon Ă©cartĂ©, la page est dans sa version actuelle.', + + /** + * Editor sidebar + */ + 'page_tags' => 'Mots-clĂ©s de la page', + 'tag' => 'Mot-clĂ©', + 'tags' => 'Mots-clĂ©', + 'tag_value' => 'Valeur du mot-clĂ© (Optionnel)', + 'tags_explain' => "Ajouter des mot-clĂ©s pour catĂ©goriser votre contenu.", + 'tags_add' => 'Ajouter un autre mot-clĂ©', + 'attachments' => 'Fichiers joints', + 'attachments_explain' => 'Ajouter des fichiers ou des liens pour les afficher sur votre page. Ils seront affichĂ©s dans la barre latĂ©rale', + 'attachments_explain_instant_save' => 'Ces changements sont enregistrĂ©s immĂ©diatement.', + 'attachments_items' => 'Fichiers joints', + 'attachments_upload' => 'Uploader un fichier', + 'attachments_link' => 'Attacher un lien', + 'attachments_set_link' => 'DĂ©finir un lien', + 'attachments_delete_confirm' => 'Cliquer une seconde fois sur supprimer pour valider la suppression.', + 'attachments_dropzone' => 'Glissez des fichiers ou cliquez ici pour attacher des fichiers', + 'attachments_no_files' => 'Aucun fichier ajoutĂ©', + 'attachments_explain_link' => 'Vous pouvez attacher un lien si vous ne souhaitez pas uploader un fichier.', + 'attachments_link_name' => 'Nom du lien', + 'attachment_link' => 'Lien de l\'attachement', + 'attachments_link_url' => 'Lien sur un fichier', + 'attachments_link_url_hint' => 'URL du site ou du fichier', + 'attach' => 'Attacher', + 'attachments_edit_file' => 'Modifier le fichier', + 'attachments_edit_file_name' => 'Nom du fichier', + 'attachments_edit_drop_upload' => 'Glissez un fichier ou cliquer pour mettre Ă  jour le fichier', + 'attachments_order_updated' => 'Ordre des fichiers joints mis Ă  jour', + 'attachments_updated_success' => 'DĂ©tails des fichiers joints mis Ă  jour', + 'attachments_deleted' => 'Fichier joint supprimĂ©', + 'attachments_file_uploaded' => 'Fichier ajoutĂ© avec succès', + 'attachments_file_updated' => 'Fichier mis Ă  jour avec succès', + 'attachments_link_attached' => 'Lien attachĂ© Ă  la page avec succès', + + /** + * Profile View + */ + 'profile_user_for_x' => 'Utilisateur depuis :time', + 'profile_created_content' => 'Contenu créé', + 'profile_not_created_pages' => ':userName n\'a pas créé de pages', + 'profile_not_created_chapters' => ':userName n\'a pas créé de chapitres', + 'profile_not_created_books' => ':userName n\'a pas créé de livres', +]; diff --git a/resources/lang/fr/errors.php b/resources/lang/fr/errors.php new file mode 100644 index 000000000..72af89f7f --- /dev/null +++ b/resources/lang/fr/errors.php @@ -0,0 +1,70 @@ + '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.', +]; diff --git a/resources/lang/fr/pagination.php b/resources/lang/fr/pagination.php new file mode 100644 index 000000000..9f07a5f93 --- /dev/null +++ b/resources/lang/fr/pagination.php @@ -0,0 +1,19 @@ + '« PrĂ©cĂ©dent', + 'next' => 'Suivant »', + +]; diff --git a/resources/lang/fr/passwords.php b/resources/lang/fr/passwords.php new file mode 100644 index 000000000..7be81da23 --- /dev/null +++ b/resources/lang/fr/passwords.php @@ -0,0 +1,22 @@ + '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Ă©!', + +]; diff --git a/resources/lang/fr/settings.php b/resources/lang/fr/settings.php new file mode 100644 index 000000000..8a3756527 --- /dev/null +++ b/resources/lang/fr/settings.php @@ -0,0 +1,112 @@ + '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 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.
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.
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.
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', + +]; diff --git a/resources/lang/fr/validation.php b/resources/lang/fr/validation.php new file mode 100644 index 000000000..9204f4e2d --- /dev/null +++ b/resources/lang/fr/validation.php @@ -0,0 +1,108 @@ + ':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' => [], + +]; diff --git a/resources/lang/pt_BR/activities.php b/resources/lang/pt_BR/activities.php new file mode 100644 index 000000000..1f5bc3528 --- /dev/null +++ b/resources/lang/pt_BR/activities.php @@ -0,0 +1,40 @@ + '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', + +]; diff --git a/resources/lang/pt_BR/auth.php b/resources/lang/pt_BR/auth.php new file mode 100644 index 000000000..ec3b92def --- /dev/null +++ b/resources/lang/pt_BR/auth.php @@ -0,0 +1,74 @@ + '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 diff --git a/resources/lang/pt_BR/common.php b/resources/lang/pt_BR/common.php new file mode 100644 index 000000000..820ba219c --- /dev/null +++ b/resources/lang/pt_BR/common.php @@ -0,0 +1,58 @@ + '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 diff --git a/resources/lang/pt_BR/components.php b/resources/lang/pt_BR/components.php new file mode 100644 index 000000000..5c1ec4241 --- /dev/null +++ b/resources/lang/pt_BR/components.php @@ -0,0 +1,24 @@ + '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 diff --git a/resources/lang/pt_BR/entities.php b/resources/lang/pt_BR/entities.php new file mode 100644 index 000000000..a6e670353 --- /dev/null +++ b/resources/lang/pt_BR/entities.php @@ -0,0 +1,226 @@ + 'Recentemente criado', + 'recently_created_pages' => 'Páginas recentemente criadas', + 'recently_updated_pages' => 'Páginas recentemente atualizadas', + 'recently_created_chapters' => 'CapĂ­tulos recentemente criados', + 'recently_created_books' => 'Livros recentemente criados', + 'recently_update' => 'Recentemente atualizado', + 'recently_viewed' => 'Recentemente visualizado', + 'recent_activity' => 'Atividade recente', + 'create_now' => 'Criar um agora', + 'revisions' => 'Revisões', + 'meta_created' => 'Criado em :timeLength', + 'meta_created_name' => 'Criado em :timeLength por :user', + 'meta_updated' => 'Atualizado em :timeLength', + 'meta_updated_name' => 'Atualizado em :timeLength por :user', + 'x_pages' => ':count Páginas', + 'entity_select' => 'Seleção de Entidade', + 'images' => 'Imagens', + 'my_recent_drafts' => 'Meus rascunhos recentes', + 'my_recently_viewed' => 'Meus itens recentemente visto', + 'no_pages_viewed' => 'VocĂŞ nĂŁo visualizou nenhuma página', + 'no_pages_recently_created' => 'Nenhuma página recentemente criada', + 'no_pages_recently_updated' => 'Nenhuma página recentemente atualizada', + + /** + * Permissions and restrictions + */ + 'permissions' => 'Permissões', + 'permissions_intro' => 'Uma vez habilitado, as permissões terĂŁo prioridade sobre outro conjunto de permissões.', + 'permissions_enable' => 'Habilitar Permissões Customizadas', + 'permissions_save' => 'Salvar Permissões', + + /** + * Search + */ + 'search_results' => 'Resultado(s) da Pesquisa', + 'search_results_page' => 'Resultado(s) de Pesquisa de Página', + 'search_results_chapter' => 'Resultado(s) de Pesquisa de CapĂ­tulo', + 'search_results_book' => 'Resultado(s) de Pesquisa de Livro', + 'search_clear' => 'Limpar Pesquisa', + 'search_view_pages' => 'Visualizar todas as páginas correspondentes', + 'search_view_chapters' => 'Visualizar todos os capĂ­tulos correspondentes', + 'search_view_books' => 'Visualizar todos os livros correspondentes', + 'search_no_pages' => 'Nenhuma página corresponde Ă  pesquisa', + 'search_for_term' => 'Pesquisar por :term', + 'search_page_for_term' => 'Pesquisar Página por :term', + 'search_chapter_for_term' => 'Pesquisar CapĂ­tulo por :term', + 'search_book_for_term' => 'Pesquisar Livros por :term', + + /** + * Books + */ + 'book' => 'Livro', + 'books' => 'Livros', + 'books_empty' => 'Nenhum livro foi criado', + 'books_popular' => 'Livros populares', + 'books_recent' => 'Livros recentes', + 'books_popular_empty' => 'Os livros mais populares aparecerĂŁo aqui.', + 'books_create' => 'Criar novo Livro', + 'books_delete' => 'Excluir Livro', + 'books_delete_named' => 'Excluir Livro :bookName', + 'books_delete_explain' => 'A ação vai excluĂ­r o livro com o nome \':bookName\'. Todas as páginas e capĂ­tulos serĂŁo removidos.', + 'books_delete_confirmation' => 'VocĂŞ tem certeza que quer excluĂ­r o Livro?', + 'books_edit' => 'Editar Livro', + 'books_edit_named' => 'Editar Livro :bookName', + 'books_form_book_name' => 'Nome do Livro', + 'books_save' => 'Salvar Livro', + 'books_permissions' => 'Permissões do Livro', + 'books_permissions_updated' => 'Permissões do Livro Atualizadas', + 'books_empty_contents' => 'Nenhuma página ou capĂ­tulo criado para esse livro.', + 'books_empty_create_page' => 'Criar uma nova página', + 'books_empty_or' => 'ou', + 'books_empty_sort_current_book' => 'Ordenar o livro atual', + 'books_empty_add_chapter' => 'Adicionar um capĂ­tulo', + 'books_permissions_active' => 'Permissões do Livro ativadas', + 'books_search_this' => 'Pesquisar esse livro', + 'books_navigation' => 'Navegação do Livro', + 'books_sort' => 'Ordenar conteĂşdos do Livro', + 'books_sort_named' => 'Ordenar Livro :bookName', + 'books_sort_show_other' => 'Mostrar outros livros', + 'books_sort_save' => 'Salvar nova ordenação', + + /** + * Chapters + */ + 'chapter' => 'Capitulo', + 'chapters' => 'CapĂ­tulos', + 'chapters_popular' => 'CapĂ­tulos Populares', + 'chapters_new' => 'Novo CapĂ­tulo', + 'chapters_create' => 'Criar novo CapĂ­tulo', + 'chapters_delete' => 'ExcluĂ­r CapĂ­tulo', + 'chapters_delete_named' => 'Excluir CapĂ­tulo :chapterName', + 'chapters_delete_explain' => 'A ação vai excluĂ­r o capĂ­tulo de nome \':chapterName\'. Todas as páginas do capĂ­tulo serĂŁo removidas + e adicionadas diretamente ao livro pai.', + 'chapters_delete_confirm' => 'Tem certeza que deseja excluĂ­r o capitulo?', + 'chapters_edit' => 'Editar CapĂ­tulo', + 'chapters_edit_named' => 'Editar capitulo :chapterName', + 'chapters_save' => 'Salvar CapĂ­tulo', + 'chapters_move' => 'Mover CapĂ­tulo', + 'chapters_move_named' => 'Mover CapĂ­tulo :chapterName', + 'chapter_move_success' => 'CapĂ­tulo movido para :bookName', + 'chapters_permissions' => 'Permissões do CapĂ­tulo', + 'chapters_empty' => 'Nenhuma página existente nesse capĂ­tulo.', + 'chapters_permissions_active' => 'Permissões de CapĂ­tulo ativadas', + 'chapters_permissions_success' => 'Permissões de CapĂ­tulo atualizadas', + + /** + * Pages + */ + 'page' => 'Página', + 'pages' => 'Páginas', + 'pages_popular' => 'Páginas Popular', + 'pages_new' => 'Nova Página', + 'pages_attachments' => 'Anexos', + 'pages_navigation' => 'Página de Navegação', + 'pages_delete' => 'ExcluĂ­r Página', + 'pages_delete_named' => 'ExcluĂ­r Página :pageName', + 'pages_delete_draft_named' => 'Excluir rascunho de Página de nome :pageName', + 'pages_delete_draft' => 'Excluir rascunho de Página', + 'pages_delete_success' => 'Página excluĂ­da', + 'pages_delete_draft_success' => 'Página de rascunho excluĂ­da', + 'pages_delete_confirm' => 'Tem certeza que deseja excluir a página?', + 'pages_delete_draft_confirm' => 'Tem certeza que deseja excluir o rascunho de página?', + 'pages_editing_named' => 'Editando a Página :pageName', + 'pages_edit_toggle_header' => 'Alternar cabeçalho', + 'pages_edit_save_draft' => 'Salvar Rascunho', + 'pages_edit_draft' => 'Editar rascunho de Página', + 'pages_editing_draft' => 'Editando Rascunho', + 'pages_editing_page' => 'Editando Página', + 'pages_edit_draft_save_at' => 'Rascunho salvo em ', + 'pages_edit_delete_draft' => 'Excluir rascunho', + 'pages_edit_discard_draft' => 'Descartar rascunho', + 'pages_edit_set_changelog' => 'Definir Changelog', + 'pages_edit_enter_changelog_desc' => 'Digite uma breve descrição das mudanças efetuadas por vocĂŞ', + 'pages_edit_enter_changelog' => 'Entrar no Changelog', + 'pages_save' => 'Salvar Página', + 'pages_title' => 'TĂ­tulo de Página', + 'pages_name' => 'Nome da Página', + 'pages_md_editor' => 'Editor', + 'pages_md_preview' => 'Preview', + 'pages_md_insert_image' => 'Inserir Imagem', + 'pages_md_insert_link' => 'Inserir Link para Entidade', + 'pages_not_in_chapter' => 'Página nĂŁo está dentro de um CapĂ­tulo', + 'pages_move' => 'Mover Página', + 'pages_move_success' => 'Pagina movida para ":parentName"', + 'pages_permissions' => 'Permissões de Página', + 'pages_permissions_success' => 'Permissões de Página atualizadas', + 'pages_revisions' => 'Revisões de Página', + 'pages_revisions_named' => 'Revisões de Página para :pageName', + 'pages_revision_named' => 'RevisĂŁo de Página para :pageName', + 'pages_revisions_created_by' => 'Criado por', + 'pages_revisions_date' => 'Data da RevisĂŁo', + 'pages_revisions_changelog' => 'Changelog', + 'pages_revisions_changes' => 'Mudanças', + 'pages_revisions_current' => 'VersĂŁo atual', + 'pages_revisions_preview' => 'Preview', + 'pages_revisions_restore' => 'Restaurar', + 'pages_revisions_none' => 'Essa página nĂŁo tem revisões', + 'pages_export' => 'Exportar', + 'pages_export_html' => 'Arquivo Web Contained', + 'pages_export_pdf' => 'Arquivo PDF', + 'pages_export_text' => 'Arquivo Texto', + 'pages_copy_link' => 'Copia Link', + 'pages_permissions_active' => 'Permissões de Página Ativas', + 'pages_initial_revision' => 'Publicação Inicial', + 'pages_initial_name' => 'Nova Página', + 'pages_editing_draft_notification' => 'VocĂŞ está atualmente editando um rascunho que foi salvo da Ăşltima vez em :timeDiff.', + 'pages_draft_edited_notification' => 'Essa página foi atualizada desde entĂŁo. É recomendado que vocĂŞ descarte esse rascunho.', + 'pages_draft_edit_active' => [ + 'start_a' => ':count usuários que iniciaram edição dessa página', + 'start_b' => ':userName iniciou a edição dessa página', + 'time_a' => 'desde que a página foi atualizada pela Ăşltima vez', + 'time_b' => 'nos Ăşltimos :minCount minutos', + 'message' => ':start :time. Tome cuidado para nĂŁo sobrescrever atualizações de outras pessoas!', + ], + 'pages_draft_discarded' => 'Rascunho descartado. O editor foi atualizado com a página atualizada', + + /** + * Editor sidebar + */ + 'page_tags' => 'Tags de Página', + 'tag' => 'Tag', + 'tags' => '', + 'tag_value' => 'Valor da Tag (Opcional)', + 'tags_explain' => "Adicione algumas tags para melhor categorizar seu conteĂşdo. \n VocĂŞ pode atrelar um valor para uma tag para uma organização mais consistente.", + 'tags_add' => 'Adicionar outra tag', + 'attachments' => 'Anexos', + 'attachments_explain' => 'Faça o Upload de alguns arquivos ou anexo algum link para ser mostrado na sua página. Eles estarĂŁo visĂ­veis na barra lateral Ă  direita da página.', + 'attachments_explain_instant_save' => 'Mudanças sĂŁo salvas instantaneamente.', + 'attachments_items' => 'Itens Anexados', + 'attachments_upload' => 'Upload de arquivos', + 'attachments_link' => 'Links Anexados', + 'attachments_set_link' => 'Definir Link', + 'attachments_delete_confirm' => 'Clique novamente em Excluir para confirmar a exclusĂŁo desse anexo.', + 'attachments_dropzone' => 'Arraste arquivos para cá ou clique para anexar arquivos', + 'attachments_no_files' => 'Nenhum arquivo foi enviado', + 'attachments_explain_link' => 'VocĂŞ pode anexar um link se preferir nĂŁo fazer o upload do arquivo. O link poderá ser para uma outra página ou link para um arquivo na nuvem.', + 'attachments_link_name' => 'Nome do Link', + 'attachment_link' => 'Link para o Anexo', + 'attachments_link_url' => 'Link para o Arquivo', + 'attachments_link_url_hint' => 'URL do site ou arquivo', + 'attach' => 'Anexar', + 'attachments_edit_file' => 'Editar Arquivo', + 'attachments_edit_file_name' => 'Nome do Arquivo', + 'attachments_edit_drop_upload' => 'Arraste arquivos para cá ou clique para anexar arquivos e sobrescreve-lo', + 'attachments_order_updated' => 'Ordem dos anexos atualizada', + 'attachments_updated_success' => 'Detalhes dos anexos atualizados', + 'attachments_deleted' => 'Anexo excluĂ­do', + 'attachments_file_uploaded' => 'Upload de arquivo efetuado com sucesso', + 'attachments_file_updated' => 'Arquivo atualizado com sucesso', + 'attachments_link_attached' => 'Link anexado com sucesso Ă  página', + + /** + * Profile View + */ + 'profile_user_for_x' => 'Usuário por :time', + 'profile_created_content' => 'ConteĂşdo Criado', + 'profile_not_created_pages' => ':userName nĂŁo criou páginas', + 'profile_not_created_chapters' => ':userName nĂŁo criou capĂ­tulos', + 'profile_not_created_books' => ':userName nĂŁo criou livros', +]; \ No newline at end of file diff --git a/resources/lang/pt_BR/errors.php b/resources/lang/pt_BR/errors.php new file mode 100644 index 000000000..91b85e3ef --- /dev/null +++ b/resources/lang/pt_BR/errors.php @@ -0,0 +1,70 @@ + '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 diff --git a/resources/lang/pt_BR/pagination.php b/resources/lang/pt_BR/pagination.php new file mode 100644 index 000000000..6a32f34ac --- /dev/null +++ b/resources/lang/pt_BR/pagination.php @@ -0,0 +1,19 @@ + '« Anterior', + 'next' => 'PrĂłximo »', + +]; diff --git a/resources/lang/pt_BR/passwords.php b/resources/lang/pt_BR/passwords.php new file mode 100644 index 000000000..f75c24ea5 --- /dev/null +++ b/resources/lang/pt_BR/passwords.php @@ -0,0 +1,22 @@ + '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!', + +]; diff --git a/resources/lang/pt_BR/settings.php b/resources/lang/pt_BR/settings.php new file mode 100644 index 000000000..b8d062b5f --- /dev/null +++ b/resources/lang/pt_BR/settings.php @@ -0,0 +1,140 @@ + 'Configurações', + 'settings_save' => 'Salvar Configurações', + 'settings_save_success' => 'Configurações Salvas', + + /** + * App settings + */ + + 'app_settings' => 'Configurações do App', + 'app_name' => 'Nome da Aplicação', + 'app_name_desc' => 'Esse nome será mostrado no cabeçalho e em e-mails.', + 'app_name_header' => 'Mostrar o nome da Aplicação no cabeçalho?', + 'app_public_viewing' => 'Permitir visualização pĂşblica?', + 'app_secure_images' => 'Permitir upload de imagens com maior segurança?', + 'app_secure_images_desc' => 'Por questões de performance, todas as imagens sĂŁo pĂşblicas. Essa opção adiciona uma string randĂ´mica na frente da imagem. Certifique-se de que os Ă­ndices do diretĂłrios permitem o acesso fácil.', + 'app_editor' => 'Editor de Página', + 'app_editor_desc' => 'Selecione qual editor a ser usado pelos usuários para editar páginas.', + 'app_custom_html' => 'ConteĂşdo para tag HTML HEAD customizado', + 'app_custom_html_desc' => 'Quaisquer conteĂşdos aqui inseridos serĂŁo inseridos no final da seção do HTML de cada página. Essa Ă© uma maneira Ăştil de sobrescrever estilos e adicionar cĂłdigos de análise de site.', + 'app_logo' => 'Logo da Aplicação', + 'app_logo_desc' => 'A imagem deve ter 43px de altura.
Imagens mais largas devem ser reduzidas.', + 'app_primary_color' => 'Cor primária da Aplicação', + 'app_primary_color_desc' => 'Esse valor deverá ser Hexadecimal.
Deixe em branco para que o Bookstack assuma a cor padrão.', + + /** + * Registration settings + */ + + 'reg_settings' => 'Parâmetros de Registro', + 'reg_allow' => 'Permitir Registro?', + 'reg_default_role' => 'Perfil padrão para usuários após o registro', + 'reg_confirm_email' => 'Requerer confirmação por e-mail?', + 'reg_confirm_email_desc' => 'Se restrições de domínio são usadas a confirmação por e-mail será requerida e o valor abaixo será ignorado.', + 'reg_confirm_restrict_domain' => 'Restringir registro ao domínio', + 'reg_confirm_restrict_domain_desc' => 'Entre com uma lista de domínios de e-mails separados por vírgula para os quais você deseja restringir os registros. Será enviado um e-mail de confirmação para o usuário validar o e-mail antes de ser permitido interação com a aplicação.
Note que os usuários serão capazes de alterar o e-mail cadastrado após o sucesso na confirmação do registro.', + 'reg_confirm_restrict_domain_placeholder' => 'Nenhuma restrição configurada', + + /** + * Role settings + */ + + 'roles' => 'Perfis', + 'role_user_roles' => 'Perfis de Usuário', + 'role_create' => 'Criar novo Perfil', + 'role_create_success' => 'Perfil criado com sucesso', + 'role_delete' => 'Excluir Perfil', + 'role_delete_confirm' => 'A ação vai excluír o Perfil de nome \':roleName\'.', + 'role_delete_users_assigned' => 'Esse Perfil tem :userCount usuários assinalados a ele. Se quiser migrar usuários desse Perfil para outro, selecione um novo Perfil.', + 'role_delete_no_migration' => "Não migre os usuários", + 'role_delete_sure' => 'Tem certeza que deseja excluir esse Perfil?', + 'role_delete_success' => 'Perfil excluído com sucesso', + 'role_edit' => 'Editar Perfil', + 'role_details' => 'Detalhes do Perfil', + 'role_name' => 'Nome do Perfil', + 'role_desc' => 'Descrição Curta do Perfil', + 'role_system' => 'Permissões do Sistema', + 'role_manage_users' => 'Gerenciar Usuários', + 'role_manage_roles' => 'Gerenciar Perfis & Permissões de Perfis', + 'role_manage_entity_permissions' => 'Gerenciar todos os livros, capítulos e permissões de páginas', + 'role_manage_own_entity_permissions' => 'Gerenciar permissões de seu próprio livro, capítulo e paginas', + 'role_manage_settings' => 'Gerenciar configurações de app', + 'role_asset' => 'Permissões de Ativos', + 'role_asset_desc' => 'Essas permissões controlam o acesso padrão para os ativos dentro do sistema. Permissões em Livros, Capítulos e Páginas serão sobrescritas por essas permissões.', + 'role_all' => 'Todos', + 'role_own' => 'Próprio', + 'role_controlled_by_asset' => 'Controlado pelos ativos que você fez upload', + 'role_save' => 'Salvar Perfil', + 'role_update_success' => 'Perfil atualizado com sucesso', + 'role_users' => 'Usuários neste Perfil', + 'role_users_none' => 'Nenhum usuário está atualmente atrelado a esse Perfil', + + /** + * Users + */ + + 'users' => 'Usuários', + 'user_profile' => 'Perfil de Usuário', + 'users_add_new' => 'Adicionar Novo Usuário', + 'users_search' => 'Pesquisar Usuários', + 'users_role' => 'Perfis de Usuário', + 'users_external_auth_id' => 'ID de Autenticação Externa', + 'users_password_warning' => 'Preencha os dados abaixo caso queira modificar a sua senha:', + 'users_system_public' => 'Esse usuário representa quaisquer convidados que visitam o aplicativo. Ele não pode ser usado para login.', + 'users_delete' => 'Excluir Usuário', + 'users_delete_named' => 'Excluir :userName', + 'users_delete_warning' => 'A ação vai excluir completamente o usuário de nome \':userName\' do sistema.', + 'users_delete_confirm' => 'Tem certeza que deseja excluir esse usuário?', + 'users_delete_success' => 'Usuários excluídos com sucesso', + 'users_edit' => 'Editar usuário', + 'users_edit_profile' => 'Editar Perfil', + 'users_edit_success' => 'Usuário atualizado com sucesso', + 'users_avatar' => 'Imagem de Usuário', + 'users_avatar_desc' => 'Essa imagem deve ser um quadrado com aproximadamente 256px de altura e largura.', + 'users_social_accounts' => 'Contas Sociais', + 'users_social_accounts_info' => 'Aqui você pode conectar outras contas para acesso mais rápido. Desconectar uma conta não retira a possibilidade de acesso usando-a. Para revogar o acesso ao perfil através da conta social, você deverá fazê-lo na sua conta social.', + 'users_social_connect' => 'Contas conectadas', + 'users_social_disconnect' => 'Desconectar Conta', + 'users_social_connected' => 'Conta :socialAccount foi conectada com sucesso ao seu perfil.', + 'users_social_disconnected' => 'Conta :socialAccount foi desconectada com sucesso de seu perfil.', +]; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/resources/lang/pt_BR/validation.php b/resources/lang/pt_BR/validation.php new file mode 100644 index 000000000..451dbe99c --- /dev/null +++ b/resources/lang/pt_BR/validation.php @@ -0,0 +1,108 @@ + 'O :attribute deve ser aceito.', + 'active_url' => 'O :attribute não é uma URL válida.', + 'after' => 'O :attribute deve ser uma data posterior à data :date.', + 'alpha' => 'O :attribute deve conter apenas letras.', + 'alpha_dash' => 'O :attribute deve conter apenas letras, números e traços.', + 'alpha_num' => 'O :attribute deve conter apenas letras e números.', + 'array' => 'O :attribute deve ser uma array.', + 'before' => 'O :attribute deve ser uma data anterior à data :date.', + 'between' => [ + 'numeric' => 'O :attribute deve ter tamanho entre :min e :max.', + 'file' => 'O :attribute deve ter entre :min e :max kilobytes.', + 'string' => 'O :attribute deve ter entre :min e :max caracteres.', + 'array' => 'O :attribute deve ter entre :min e :max itens.', + ], + 'boolean' => 'O campo :attribute deve ser verdadeiro ou falso.', + 'confirmed' => 'O campo :attribute de confirmação não é igual.', + 'date' => 'O campo :attribute não está em um formato de data válido.', + 'date_format' => 'O campo :attribute não tem a formatação :format.', + 'different' => 'O campo :attribute e o campo :other devem ser diferentes.', + 'digits' => 'O campo :attribute deve ter :digits dígitos.', + 'digits_between' => 'O campo :attribute deve ter entre :min e :max dígitos.', + 'email' => 'O campo :attribute deve ser um e-mail válido.', + 'filled' => 'O campo :attribute é requerido.', + 'exists' => 'O atributo :attribute selecionado não é válido.', + 'image' => 'O campo :attribute deve ser uma imagem.', + 'in' => 'The selected :attribute is invalid.', + 'integer' => 'O campo :attribute deve ser um número inteiro.', + 'ip' => 'O campo :attribute deve ser um IP válido.', + 'max' => [ + 'numeric' => 'O valor para o campo :attribute não deve ser maior que :max.', + 'file' => 'O valor para o campo :attribute não deve ter tamanho maior que :max kilobytes.', + 'string' => 'O valor para o campo :attribute não deve ter mais que :max caracteres.', + 'array' => 'O valor para o campo :attribute não deve ter mais que :max itens.', + ], + 'mimes' => 'O :attribute deve ser do tipo type: :values.', + 'min' => [ + 'numeric' => 'O valor para o campo :attribute não deve ser menor que :min.', + 'file' => 'O valor para o campo :attribute não deve ter tamanho menor que :min kilobytes.', + 'string' => 'O valor para o campo :attribute não deve ter menos que :min caracteres.', + 'array' => 'O valor para o campo :attribute não deve ter menos que :min itens.', + ], + 'not_in' => 'O campo selecionado :attribute é inválido.', + 'numeric' => 'O campo :attribute deve ser um número.', + 'regex' => 'O formato do campo :attribute é inválido.', + 'required' => 'O campo :attribute é requerido.', + 'required_if' => 'O campo :attribute é requerido quando o campo :other tem valor :value.', + 'required_with' => 'O campo :attribute é requerido quando os valores :values estiverem presentes.', + 'required_with_all' => 'O campo :attribute é requerido quando os valores :values estiverem presentes.', + 'required_without' => 'O campo :attribute é requerido quando os valores :values não estiverem presentes.', + 'required_without_all' => 'O campo :attribute é requerido quando nenhum dos valores :values estiverem presentes.', + 'same' => 'O campo :attribute e o campo :other devem ser iguais.', + 'size' => [ + 'numeric' => 'O tamanho do campo :attribute deve ser :size.', + 'file' => 'O tamanho do arquivo :attribute deve ser de :size kilobytes.', + 'string' => 'O tamanho do campo :attribute deve ser de :size caracteres.', + 'array' => 'O campo :attribute deve conter :size itens.', + ], + 'string' => 'O campo :attribute deve ser uma string.', + 'timezone' => 'O campo :attribute deve conter uma timezone válida.', + 'unique' => 'Já existe um campo/dado de nome :attribute.', + 'url' => 'O formato da URL :attribute é inválido.', + + /* + |-------------------------------------------------------------------------- + | 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' => 'Confirmação de senha requerida', + ], + ], + + /* + |-------------------------------------------------------------------------- + | 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' => [], + +]; diff --git a/resources/views/auth/forms/login/ldap.blade.php b/resources/views/auth/forms/login/ldap.blade.php index 5230d43ca..b52b5f13e 100644 --- a/resources/views/auth/forms/login/ldap.blade.php +++ b/resources/views/auth/forms/login/ldap.blade.php @@ -1,19 +1,19 @@
- + @include('form/text', ['name' => 'username', 'tabindex' => 1])
@if(session('request-email', false) === true)
- + @include('form/text', ['name' => 'email', 'tabindex' => 1]) - Please enter an email to use for this account. + {{ trans('auth.ldap_email_hint') }}
@endif
- + @include('form/password', ['name' => 'password', 'tabindex' => 2])
\ No newline at end of file diff --git a/resources/views/auth/forms/login/standard.blade.php b/resources/views/auth/forms/login/standard.blade.php index abefd21a1..4ea1f35ba 100644 --- a/resources/views/auth/forms/login/standard.blade.php +++ b/resources/views/auth/forms/login/standard.blade.php @@ -1,10 +1,10 @@
- + @include('form/text', ['name' => 'email', 'tabindex' => 1])
- + @include('form/password', ['name' => 'password', 'tabindex' => 2]) - Forgot Password? + {{ trans('auth.forgot_password') }}
\ No newline at end of file diff --git a/resources/views/auth/login.blade.php b/resources/views/auth/login.blade.php index 4fa97c1d5..928565156 100644 --- a/resources/views/auth/login.blade.php +++ b/resources/views/auth/login.blade.php @@ -2,7 +2,7 @@ @section('header-buttons') @if(setting('registration-enabled', false)) - Sign up + {{ trans('auth.sign_up') }} @endif @stop @@ -10,7 +10,7 @@
-

Log In

+

{{ title_case(trans('auth.log_in')) }}

{!! csrf_field() !!} @@ -19,25 +19,25 @@ @include('auth/forms/login/' . $authMethod)
- +
- +
@if(count($socialDrivers) > 0)
-

Social Login

+

{{ trans('auth.social_login') }}

@if(isset($socialDrivers['google'])) - + @endif @if(isset($socialDrivers['github'])) - + @endif @endif
diff --git a/resources/views/auth/passwords/email.blade.php b/resources/views/auth/passwords/email.blade.php index 115785ab2..07bd2c383 100644 --- a/resources/views/auth/passwords/email.blade.php +++ b/resources/views/auth/passwords/email.blade.php @@ -1,9 +1,9 @@ @extends('public') @section('header-buttons') - Sign in + {{ trans('auth.log_in') }} @if(setting('registration-enabled')) - Sign up + {{ trans('auth.sign_up') }} @endif @stop @@ -12,20 +12,20 @@
-

Reset Password

+

{{ trans('auth.reset_password') }}

-

Enter your email below and you will be sent an email with a password reset link.

+

{{ trans('auth.reset_password_send_instructions') }}

{!! csrf_field() !!}
- + @include('form/text', ['name' => 'email'])
- +
diff --git a/resources/views/auth/passwords/reset.blade.php b/resources/views/auth/passwords/reset.blade.php index 612b50ff8..a463eef45 100644 --- a/resources/views/auth/passwords/reset.blade.php +++ b/resources/views/auth/passwords/reset.blade.php @@ -1,9 +1,9 @@ @extends('public') @section('header-buttons') - Sign in + {{ trans('auth.log_in') }} @if(setting('registration-enabled')) - Sign up + {{ trans('auth.sign_up') }} @endif @stop @@ -14,29 +14,29 @@
-

Reset Password

+

{{ trans('auth.reset_password') }}

{!! csrf_field() !!}
- + @include('form/text', ['name' => 'email'])
- + @include('form/password', ['name' => 'password'])
- + @include('form/password', ['name' => 'password_confirmation'])
- +
diff --git a/resources/views/auth/register-confirm.blade.php b/resources/views/auth/register-confirm.blade.php index 97fd65ab5..364df9266 100644 --- a/resources/views/auth/register-confirm.blade.php +++ b/resources/views/auth/register-confirm.blade.php @@ -2,7 +2,7 @@ @section('header-buttons') @if(!$signedIn) - Sign in + {{ trans('auth.log_in') }} @endif @stop @@ -10,10 +10,9 @@
-

Thanks for registering!

-

Please check your email and click the confirmation button to access {{ setting('app-name', 'BookStack') }}.

+

{{ trans('auth.register_thanks') }}

+

{{ trans('auth.register_confirm', ['appName' => setting('app-name')]) }}

- @stop diff --git a/resources/views/auth/register.blade.php b/resources/views/auth/register.blade.php index 8ae5fcf50..7a119ddba 100644 --- a/resources/views/auth/register.blade.php +++ b/resources/views/auth/register.blade.php @@ -1,42 +1,42 @@ @extends('public') @section('header-buttons') - Sign in + {{ trans('auth.log_in') }} @stop @section('content')
-

Sign Up

+

{{ title_case(trans('auth.sign_up')) }}

{!! csrf_field() !!}
- + @include('form/text', ['name' => 'name'])
- + @include('form/text', ['name' => 'email'])
- - @include('form/password', ['name' => 'password', 'placeholder' => 'Must be over 5 characters']) + + @include('form/password', ['name' => 'password', 'placeholder' => trans('auth.password_hint')])
- +
@if(count($socialDrivers) > 0)
-

Social Registration

-

Register and sign in using another service.

+

{{ trans('auth.social_registration') }}

+

{{ trans('auth.social_registration_text') }}

@if(isset($socialDrivers['google'])) @endif diff --git a/resources/views/auth/user-unconfirmed.blade.php b/resources/views/auth/user-unconfirmed.blade.php index 08178e891..13567b412 100644 --- a/resources/views/auth/user-unconfirmed.blade.php +++ b/resources/views/auth/user-unconfirmed.blade.php @@ -4,16 +4,16 @@
-

Email Address not confirmed

-

Your email address has not yet been confirmed.
- Please click the link in the email that was sent shortly after you registered.
- If you cannot find the email you can re-send the confirmation email by submitting the form below. +

{{ trans('auth.email_not_confirmed') }}

+

{{ trans('auth.email_not_confirmed_text') }}
+ {{ trans('auth.email_not_confirmed_click_link') }}
+ {{ trans('auth.email_not_confirmed_resend') }}


{!! csrf_field() !!}
- + @if(auth()->check()) @include('form/text', ['name' => 'email', 'model' => auth()->user()]) @else @@ -21,7 +21,7 @@ @endif
- +
diff --git a/resources/views/base.blade.php b/resources/views/base.blade.php index 08acf725d..43f22d89a 100644 --- a/resources/views/base.blade.php +++ b/resources/views/base.blade.php @@ -17,6 +17,7 @@ + @yield('head') @@ -53,32 +54,16 @@
@if(isset($signedIn) && $signedIn) - + @include('partials._header-dropdown', ['currentUser' => $currentUser]) @endif
@@ -93,7 +78,7 @@
- Back to top + {{ trans('common.back_to_top') }}
@yield('bottom') diff --git a/resources/views/books/_breadcrumbs.blade.php b/resources/views/books/_breadcrumbs.blade.php new file mode 100644 index 000000000..e588127ce --- /dev/null +++ b/resources/views/books/_breadcrumbs.blade.php @@ -0,0 +1,3 @@ + \ No newline at end of file diff --git a/resources/views/books/create.blade.php b/resources/views/books/create.blade.php index 60f4f65bd..2c629e699 100644 --- a/resources/views/books/create.blade.php +++ b/resources/views/books/create.blade.php @@ -3,7 +3,7 @@ @section('content')
-

Create New Book

+

{{ trans('entities.books_create') }}

@include('books/form')
diff --git a/resources/views/books/delete.blade.php b/resources/views/books/delete.blade.php index 68f755131..0b1e67d4a 100644 --- a/resources/views/books/delete.blade.php +++ b/resources/views/books/delete.blade.php @@ -2,16 +2,26 @@ @section('content') +
+
+
+
+ @include('books._breadcrumbs', ['book' => $book]) +
+
+
+
+
-

Delete Book

-

This will delete the book with the name '{{$book->name}}', All pages and chapters will be removed.

-

Are you sure you want to delete this book?

+

{{ trans('entities.books_delete') }}

+

{{ trans('entities.books_delete_explain', ['bookName' => $book->name]) }}

+

{{ trans('entities.books_delete_confirmation') }}

{!! csrf_field() !!} - Cancel - + {{ trans('common.cancel') }} +
diff --git a/resources/views/books/edit.blade.php b/resources/views/books/edit.blade.php index e67e6f459..2419b68da 100644 --- a/resources/views/books/edit.blade.php +++ b/resources/views/books/edit.blade.php @@ -2,8 +2,18 @@ @section('content') +
+
+
+
+ @include('books._breadcrumbs', ['book' => $book]) +
+
+
+
+
-

Edit Book

+

{{ trans('entities.books_edit') }}

@include('books/form', ['model' => $book]) diff --git a/resources/views/books/form.blade.php b/resources/views/books/form.blade.php index dc0fd0a3f..514abf42c 100644 --- a/resources/views/books/form.blade.php +++ b/resources/views/books/form.blade.php @@ -1,16 +1,16 @@ {{ csrf_field() }}
- + @include('form/text', ['name' => 'name'])
- + @include('form/textarea', ['name' => 'description'])
- Cancel - + {{ trans('common.cancel') }} +
\ No newline at end of file diff --git a/resources/views/books/index.blade.php b/resources/views/books/index.blade.php index 91906e7b8..c090a127e 100644 --- a/resources/views/books/index.blade.php +++ b/resources/views/books/index.blade.php @@ -9,7 +9,7 @@
@if($currentUser->can('book-create-all')) - Add new book + {{ trans('entities.books_create') }} @endif
@@ -21,7 +21,7 @@
-

Books

+

{{ trans('entities.books') }}

@if(count($books) > 0) @foreach($books as $book) @include('books/list-item', ['book' => $book]) @@ -29,27 +29,27 @@ @endforeach {!! $books->render() !!} @else -

No books have been created.

+

{{ trans('entities.books_empty') }}

@if(userCan('books-create-all')) - Create one now + {{ trans('entities.create_one_now') }} @endif @endif
@if($recents) -
 
-

Recently Viewed

+
 
+

{{ trans('entities.recently_viewed') }}

@include('partials/entity-list', ['entities' => $recents]) @endif
 
diff --git a/resources/views/books/restrictions.blade.php b/resources/views/books/restrictions.blade.php index 7fdd3abef..f558fdfce 100644 --- a/resources/views/books/restrictions.blade.php +++ b/resources/views/books/restrictions.blade.php @@ -6,9 +6,7 @@
- + @include('books._breadcrumbs', ['book' => $book])
@@ -16,7 +14,7 @@
-

Book Permissions

+

{{ trans('entities.books_permissions') }}

@include('form/restriction-form', ['model' => $book])
diff --git a/resources/views/books/show.blade.php b/resources/views/books/show.blade.php index 129851d5e..6a18302bc 100644 --- a/resources/views/books/show.blade.php +++ b/resources/views/books/show.blade.php @@ -5,29 +5,32 @@
-
+
+ @include('books._breadcrumbs', ['book' => $book]) +
+
@if(userCan('page-create', $book)) - New Page + {{ trans('entities.pages_new') }} @endif @if(userCan('chapter-create', $book)) - New Chapter + {{ trans('entities.chapters_new') }} @endif @if(userCan('book-update', $book)) - Edit + {{ trans('common.edit') }} @endif @if(userCan('book-update', $book) || userCan('restrictions-manage', $book) || userCan('book-delete', $book)) @@ -59,23 +62,19 @@
@endforeach @else -

No pages or chapters have been created for this book.

+

{{ trans('entities.books_empty_contents') }}

- Create a new page -   -or-    - Add a chapter + {{ trans('entities.books_empty_create_page') }} +   -{{ trans('entities.books_empty_or') }}-    + {{ trans('entities.books_empty_add_chapter') }}


@endif -

- Created {{$book->created_at->diffForHumans()}} @if($book->createdBy) by {{$book->createdBy->name}} @endif -
- Last Updated {{$book->updated_at->diffForHumans()}} @if($book->updatedBy) by {{$book->updatedBy->name}} @endif -

+ @include('partials.entity-meta', ['entity' => $book])
-

Search Results Clear Search

+

{{ trans('entities.search_results') }} {{ trans('entities.search_clear') }}

@include('partials/loading-icon')
@@ -90,21 +89,21 @@ @if($book->restricted)

@if(userCan('restrictions-manage', $book)) - Book Permissions Active + {{ trans('entities.books_permissions_active') }} @else - Book Permissions Active + {{ trans('entities.books_permissions_active') }} @endif

@endif
-

Recent Activity

+

{{ trans('entities.recent_activity') }}

@include('partials/activity-list', ['activity' => Activity::entityActivity($book, 20, 0)])
diff --git a/resources/views/books/sort.blade.php b/resources/views/books/sort.blade.php index 984db0ce6..d96f502f1 100644 --- a/resources/views/books/sort.blade.php +++ b/resources/views/books/sort.blade.php @@ -6,8 +6,18 @@ @section('content') +
+
+
+
+ @include('books._breadcrumbs', ['book' => $book]) +
+
+
+
+
-

Sorting Pages & ChaptersFor {{ $book->name }}

+

{{ trans('entities.books_sort') }}

@@ -17,7 +27,7 @@ @if(count($books) > 1)
-

Show Other Books

+

{{ trans('entities.books_sort_show_other') }}

@foreach($books as $otherBook) @if($otherBook->id !== $book->id) @@ -37,8 +47,8 @@
- Cancel - + {{ trans('common.cancel') }} +
diff --git a/resources/views/chapters/_breadcrumbs.blade.php b/resources/views/chapters/_breadcrumbs.blade.php new file mode 100644 index 000000000..9064cc7c3 --- /dev/null +++ b/resources/views/chapters/_breadcrumbs.blade.php @@ -0,0 +1,5 @@ + \ No newline at end of file diff --git a/resources/views/chapters/create.blade.php b/resources/views/chapters/create.blade.php index b81cb15d7..afdbfa99d 100644 --- a/resources/views/chapters/create.blade.php +++ b/resources/views/chapters/create.blade.php @@ -3,7 +3,7 @@ @section('content')
-

Create New Chapter

+

{{ trans('entities.chapters_create') }}

@include('chapters/form')
diff --git a/resources/views/chapters/delete.blade.php b/resources/views/chapters/delete.blade.php index e9573f228..bacb8dca3 100644 --- a/resources/views/chapters/delete.blade.php +++ b/resources/views/chapters/delete.blade.php @@ -2,17 +2,26 @@ @section('content') +
+
+
+
+ @include('chapters._breadcrumbs', ['chapter' => $chapter]) +
+
+
+
+
-

Delete Chapter

-

This will delete the chapter with the name '{{$chapter->name}}', All pages will be removed - and added directly to the book.

-

Are you sure you want to delete this chapter?

+

{{ trans('entities.chapters_delete') }}

+

{{ trans('entities.chapters_delete_explain', ['chapterName' => $chapter->name]) }}

+

{{ trans('entities.chapters_delete_confirm') }}

{!! csrf_field() !!} - Cancel - + {{ trans('common.cancel') }} +
diff --git a/resources/views/chapters/edit.blade.php b/resources/views/chapters/edit.blade.php index 0363da96d..272543e67 100644 --- a/resources/views/chapters/edit.blade.php +++ b/resources/views/chapters/edit.blade.php @@ -3,7 +3,7 @@ @section('content')
-

Edit Chapter

+

{{ trans('entities.chapters_edit') }}

@include('chapters/form', ['model' => $chapter]) diff --git a/resources/views/chapters/form.blade.php b/resources/views/chapters/form.blade.php index 70df4737a..54722a58a 100644 --- a/resources/views/chapters/form.blade.php +++ b/resources/views/chapters/form.blade.php @@ -2,16 +2,16 @@ {!! csrf_field() !!}
- + @include('form/text', ['name' => 'name'])
- + @include('form/textarea', ['name' => 'description'])
- Cancel - + {{ trans('common.cancel') }} +
diff --git a/resources/views/chapters/list-item.blade.php b/resources/views/chapters/list-item.blade.php index f70e59244..8487a63a3 100644 --- a/resources/views/chapters/list-item.blade.php +++ b/resources/views/chapters/list-item.blade.php @@ -17,7 +17,7 @@ @endif @if(!isset($hidePages) && count($chapter->pages) > 0) -

{{ count($chapter->pages) }} Pages

+

{{ trans('entities.x_pages', ['count' => $chapter->pages->count()]) }}

@foreach($chapter->pages as $page)
{{$page->name}}
diff --git a/resources/views/chapters/move.blade.php b/resources/views/chapters/move.blade.php index 37d56d30d..9e6ddb521 100644 --- a/resources/views/chapters/move.blade.php +++ b/resources/views/chapters/move.blade.php @@ -6,27 +6,23 @@
- + @include('chapters._breadcrumbs', ['chapter' => $chapter])
-

Move Chapter {{$chapter->name}}

+

{{ trans('entities.chapters_move') }}

{!! csrf_field() !!} - @include('partials/entity-selector', ['name' => 'entity_selection', 'selectorSize' => 'large', 'entityTypes' => 'book']) + @include('components.entity-selector', ['name' => 'entity_selection', 'selectorSize' => 'large', 'entityTypes' => 'book']) - Cancel - + {{ trans('common.cancel') }} +
diff --git a/resources/views/chapters/restrictions.blade.php b/resources/views/chapters/restrictions.blade.php index 771665037..7b908ee15 100644 --- a/resources/views/chapters/restrictions.blade.php +++ b/resources/views/chapters/restrictions.blade.php @@ -6,18 +6,14 @@
- + @include('chapters._breadcrumbs', ['chapter' => $chapter])
-

Chapter Permissions

+

{{ trans('entities.chapters_permissions') }}

@include('form/restriction-form', ['model' => $chapter])
diff --git a/resources/views/chapters/show.blade.php b/resources/views/chapters/show.blade.php index 70b09e9ce..93eee6424 100644 --- a/resources/views/chapters/show.blade.php +++ b/resources/views/chapters/show.blade.php @@ -6,30 +6,28 @@
- + @include('chapters._breadcrumbs', ['chapter' => $chapter])
@if(userCan('page-create', $chapter)) - New Page + {{ trans('entities.pages_new') }} @endif @if(userCan('chapter-update', $chapter)) - Edit + {{ trans('common.edit') }} @endif @if(userCan('chapter-update', $chapter) || userCan('restrictions-manage', $chapter) || userCan('chapter-delete', $chapter)) @@ -57,26 +55,22 @@
@else
-

No pages are currently in this chapter.

+

{{ trans('entities.chapters_empty') }}

@if(userCan('page-create', $chapter)) - Create a new page + {{ trans('entities.books_empty_create_page') }} @endif @if(userCan('page-create', $chapter) && userCan('book-update', $book)) -   -or-    +   -{{ trans('entities.books_empty_or') }}-    @endif @if(userCan('book-update', $book)) - Sort the current book + {{ trans('entities.books_empty_sort_current_book') }} @endif


@endif -

- Created {{ $chapter->created_at->diffForHumans() }} @if($chapter->createdBy) by {{ $chapter->createdBy->name}} @endif -
- Last Updated {{ $chapter->updated_at->diffForHumans() }} @if($chapter->updatedBy) by {{ $chapter->updatedBy->name}} @endif -

+ @include('partials.entity-meta', ['entity' => $chapter])
@@ -84,19 +78,20 @@
@if($book->restricted) - @if(userCan('restrictions-manage', $book)) - Book Permissions Active - @else - Book Permissions Active - @endif -
+

+ @if(userCan('restrictions-manage', $book)) + {{ trans('entities.books_permissions_active') }} + @else + {{ trans('entities.books_permissions_active') }} + @endif +

@endif @if($chapter->restricted) @if(userCan('restrictions-manage', $chapter)) - Chapter Permissions Active + {{ trans('entities.chapters_permissions_active') }} @else - Chapter Permissions Active + {{ trans('entities.chapters_permissions_active') }} @endif @endif
diff --git a/resources/views/partials/entity-selector-popup.blade.php b/resources/views/components/entity-selector-popup.blade.php similarity index 63% rename from resources/views/partials/entity-selector-popup.blade.php rename to resources/views/components/entity-selector-popup.blade.php index b9166896a..1c4d1fadb 100644 --- a/resources/views/partials/entity-selector-popup.blade.php +++ b/resources/views/components/entity-selector-popup.blade.php @@ -2,12 +2,12 @@
diff --git a/resources/views/partials/entity-selector.blade.php b/resources/views/components/entity-selector.blade.php similarity index 66% rename from resources/views/partials/entity-selector.blade.php rename to resources/views/components/entity-selector.blade.php index 59e174155..8fb2187e6 100644 --- a/resources/views/partials/entity-selector.blade.php +++ b/resources/views/components/entity-selector.blade.php @@ -1,8 +1,8 @@
- -
@include('partials/loading-icon')
+ +
@include('partials.loading-icon')
\ No newline at end of file diff --git a/resources/views/partials/image-manager.blade.php b/resources/views/components/image-manager.blade.php similarity index 70% rename from resources/views/partials/image-manager.blade.php rename to resources/views/components/image-manager.blade.php index 83625ad88..39f3bcd3c 100644 --- a/resources/views/partials/image-manager.blade.php +++ b/resources/views/components/image-manager.blade.php @@ -3,7 +3,7 @@
@@ -51,15 +51,14 @@
- +

- This image is used in the pages below, Click delete again to confirm you want to delete - this image. + {{ trans('components.image_delete_confirm') }}

  • @@ -73,13 +72,13 @@
- +
diff --git a/resources/views/components/image-picker.blade.php b/resources/views/components/image-picker.blade.php new file mode 100644 index 000000000..47fb2b8b7 --- /dev/null +++ b/resources/views/components/image-picker.blade.php @@ -0,0 +1,66 @@ +
+ +
+ {{ trans('components.image_preview') }} +
+ + +
+ + + @if ($showRemove) + | + + @endif + + +
+ + \ No newline at end of file diff --git a/resources/views/components/toggle-switch.blade.php b/resources/views/components/toggle-switch.blade.php new file mode 100644 index 000000000..ad54d5ab1 --- /dev/null +++ b/resources/views/components/toggle-switch.blade.php @@ -0,0 +1,15 @@ +
+ +
+
+ \ No newline at end of file diff --git a/resources/views/errors/404.blade.php b/resources/views/errors/404.blade.php index 19565bccb..c9e600ceb 100644 --- a/resources/views/errors/404.blade.php +++ b/resources/views/errors/404.blade.php @@ -4,9 +4,28 @@
-

{{ $message or 'Page Not Found' }}

-

Sorry, The page you were looking for could not be found.

- Return To Home + + +

{{ $message or trans('errors.404_page_not_found') }}

+

{{ trans('errors.sorry_page_not_found') }}

+

{{ trans('errors.return_home') }}

+ +
+ +
+
+

{{ trans('entities.pages_popular') }}

+ @include('partials.entity-list', ['entities' => Views::getPopular(10, 0, [\BookStack\Page::class]), 'style' => 'compact']) +
+
+

{{ trans('entities.books_popular') }}

+ @include('partials.entity-list', ['entities' => Views::getPopular(10, 0, [\BookStack\Book::class]), 'style' => 'compact']) +
+
+

{{ trans('entities.chapters_popular') }}

+ @include('partials.entity-list', ['entities' => Views::getPopular(10, 0, [\BookStack\Chapter::class]), 'style' => 'compact']) +
+
@stop \ No newline at end of file diff --git a/resources/views/errors/500.blade.php b/resources/views/errors/500.blade.php index 2a58461ba..6dd96cdcc 100644 --- a/resources/views/errors/500.blade.php +++ b/resources/views/errors/500.blade.php @@ -3,7 +3,7 @@ @section('content')
-

An Error Occurred

+

{{ trans('errors.error_occurred') }}

{{ $message }}

diff --git a/resources/views/errors/503.blade.php b/resources/views/errors/503.blade.php index c79d0f68b..1ea39a7b8 100644 --- a/resources/views/errors/503.blade.php +++ b/resources/views/errors/503.blade.php @@ -3,8 +3,8 @@ @section('content')
-

{{ setting('app-name') }} is down right now

-

It will be back up soon.

+

{{ trans('errors.app_down', ['appName' => setting('app-name')]) }}

+

{{ trans('errors.back_soon') }}

@stop \ No newline at end of file diff --git a/resources/views/form/delete-button.blade.php b/resources/views/form/delete-button.blade.php index a5b1f2809..6c53effae 100644 --- a/resources/views/form/delete-button.blade.php +++ b/resources/views/form/delete-button.blade.php @@ -1,5 +1,5 @@
{{ csrf_field() }} - +
\ No newline at end of file diff --git a/resources/views/form/restriction-form.blade.php b/resources/views/form/restriction-form.blade.php index 7472fe65e..7a1605197 100644 --- a/resources/views/form/restriction-form.blade.php +++ b/resources/views/form/restriction-form.blade.php @@ -2,31 +2,31 @@ {!! csrf_field() !!} -

Once enabled, These permissions will take priority over any set role permissions.

+

{{ trans('entities.permissions_intro') }}

- @include('form/checkbox', ['name' => 'restricted', 'label' => 'Enable custom permissions']) + @include('form/checkbox', ['name' => 'restricted', 'label' => trans('entities.permissions_enable')])
- - + + @foreach($roles as $role) - + @if(!$model->isA('page')) - + @endif - - + + @endforeach
RoleisA('page')) colspan="3" @else colspan="4" @endif>Actions{{ trans('common.role') }}isA('page')) colspan="3" @else colspan="4" @endif>{{ trans('common.actions') }}
{{ $role->display_name }}@include('form/restriction-checkbox', ['name'=>'restrictions', 'label' => 'View', 'action' => 'view'])@include('form/restriction-checkbox', ['name'=>'restrictions', 'label' => trans('common.view'), 'action' => 'view'])@include('form/restriction-checkbox', ['name'=>'restrictions', 'label' => 'Create', 'action' => 'create'])@include('form/restriction-checkbox', ['name'=>'restrictions', 'label' => trans('common.create'), 'action' => 'create'])@include('form/restriction-checkbox', ['name'=>'restrictions', 'label' => 'Update', 'action' => 'update'])@include('form/restriction-checkbox', ['name'=>'restrictions', 'label' => 'Delete', 'action' => 'delete'])@include('form/restriction-checkbox', ['name'=>'restrictions', 'label' => trans('common.update'), 'action' => 'update'])@include('form/restriction-checkbox', ['name'=>'restrictions', 'label' => trans('common.delete'), 'action' => 'delete'])
- Cancel - + {{ trans('common.cancel') }} + \ No newline at end of file diff --git a/resources/views/home.blade.php b/resources/views/home.blade.php index 2fb4ac855..49cd2a75a 100644 --- a/resources/views/home.blade.php +++ b/resources/views/home.blade.php @@ -5,14 +5,9 @@
- @@ -25,44 +20,44 @@
@if(count($draftPages) > 0) -

My Recent Drafts

+

{{ trans('entities.my_recent_drafts') }}

@include('partials/entity-list', ['entities' => $draftPages, 'style' => 'compact']) @endif
@if($signedIn) -

My Recently Viewed

+

{{ trans('entities.my_recently_viewed') }}

@else -

Recent Books

+

{{ trans('entities.books_recent') }}

@endif @include('partials/entity-list', [ 'entities' => $recents, 'style' => 'compact', - 'emptyText' => $signedIn ? 'You have not viewed any pages' : 'No books have been created' + 'emptyText' => $signedIn ? trans('entities.no_pages_viewed') : trans('entities.books_empty') ])
-

Recently Created Pages

+

{{ trans('entities.recently_created_pages') }}

@include('partials/entity-list', [ 'entities' => $recentlyCreatedPages, 'style' => 'compact', - 'emptyText' => 'No pages have been recently created' + 'emptyText' => trans('entities.no_pages_recently_created') ])
-

Recently Updated Pages

+

{{ trans('entities.recently_updated_pages') }}

@include('partials/entity-list', [ 'entities' => $recentlyUpdatedPages, 'style' => 'compact', - 'emptyText' => 'No pages have been recently updated' + 'emptyText' => trans('entities.no_pages_recently_updated') ])
-

Recent Activity

+

{{ trans('entities.recent_activity') }}

@include('partials/activity-list', ['activity' => $activity])
@@ -70,4 +65,4 @@
-@stop \ No newline at end of file +@stop diff --git a/resources/views/pages/_breadcrumbs.blade.php b/resources/views/pages/_breadcrumbs.blade.php new file mode 100644 index 000000000..0d2a61ab2 --- /dev/null +++ b/resources/views/pages/_breadcrumbs.blade.php @@ -0,0 +1,12 @@ + \ No newline at end of file diff --git a/resources/views/pages/delete.blade.php b/resources/views/pages/delete.blade.php index 57cc86054..f94a614fb 100644 --- a/resources/views/pages/delete.blade.php +++ b/resources/views/pages/delete.blade.php @@ -2,15 +2,25 @@ @section('content') +
+
+
+
+ @include('pages._breadcrumbs', ['page' => $page]) +
+
+
+
+
-

Delete {{ $page->draft ? 'Draft' : '' }} Page

-

Are you sure you want to delete this {{ $page->draft ? 'draft' : '' }} page?

+

{{ $page->draft ? trans('entities.pages_delete_draft') : trans('entities.pages_delete') }}

+

{{ $page->draft ? trans('entities.pages_delete_draft_confirm'): trans('entities.pages_delete_confirm') }}

{!! csrf_field() !!} - Cancel - + {{ trans('common.cancel') }} +
diff --git a/resources/views/pages/edit.blade.php b/resources/views/pages/edit.blade.php index e50cc7c5b..e1c0a169d 100644 --- a/resources/views/pages/edit.blade.php +++ b/resources/views/pages/edit.blade.php @@ -20,7 +20,7 @@
- @include('partials/image-manager', ['imageType' => 'gallery', 'uploaded_to' => $page->id]) - @include('partials/entity-selector-popup') + @include('components.image-manager', ['imageType' => 'gallery', 'uploaded_to' => $page->id]) + @include('components.entity-selector-popup') @stop \ No newline at end of file diff --git a/resources/views/pages/export.blade.php b/resources/views/pages/export.blade.php index 96f06290e..19a635563 100644 --- a/resources/views/pages/export.blade.php +++ b/resources/views/pages/export.blade.php @@ -15,15 +15,11 @@
- @include('pages/page-display') + @include('pages.page-display')
-

- Created {{$page->created_at->toDayDateTimeString()}} @if($page->createdBy) by {{$page->createdBy->name}} @endif -
- Last Updated {{$page->updated_at->toDayDateTimeString()}} @if($page->updatedBy) by {{$page->updatedBy->name}} @endif -

+ @include('partials.entity-meta', ['entity' => $page])
diff --git a/resources/views/pages/form-toolbox.blade.php b/resources/views/pages/form-toolbox.blade.php index a6e66a24a..ecf7619b7 100644 --- a/resources/views/pages/form-toolbox.blade.php +++ b/resources/views/pages/form-toolbox.blade.php @@ -3,22 +3,22 @@
- + @if(userCan('attachment-create-all')) - + @endif
-

Page Tags

+

{{ trans('entities.page_tags') }}

-

Add some tags to better categorise your content.
You can assign a value to a tag for more in-depth organisation.

+

{!! nl2br(e(trans('entities.tags_explain'))) !!}

- - + + @@ -28,7 +28,7 @@ @@ -39,17 +39,17 @@ @if(userCan('attachment-create-all'))
-

Attachments

+

{{ trans('entities.attachments') }}

-

Upload some files or attach some link to display on your page. These are visible in the page sidebar. Changes here are saved instantly.

+

{{ trans('entities.attachments_explain') }} {{ trans('entities.attachments_explain_instant_save') }}

- +
@@ -59,9 +59,9 @@ @@ -71,25 +71,25 @@
- Click delete again to confirm you want to delete this attachment. + {{ trans('entities.attachments_delete_confirm') }}
- Cancel + {{ trans('common.cancel') }}

- No files have been uploaded. + {{ trans('entities.attachments_no_files') }}

- +
-

You can attach a link if you'd prefer not to upload a file. This can be a link to another page or a link to a file in the cloud.

+

{{ trans('entities.attachments_explain_link') }}

- - + +

- - + +

- +
@@ -97,34 +97,34 @@
-
Edit File
+
{{ trans('entities.attachments_edit_file') }}
- - + +

- +
- - + +

- - + +
diff --git a/resources/views/pages/form.blade.php b/resources/views/pages/form.blade.php index c4baf38f7..eb5ebb0bd 100644 --- a/resources/views/pages/form.blade.php +++ b/resources/views/pages/form.blade.php @@ -9,8 +9,8 @@
@@ -34,16 +34,16 @@
- +
@@ -53,7 +53,7 @@ {{--Title input--}}
- @include('form/text', ['name' => 'name', 'placeholder' => 'Page Title']) + @include('form/text', ['name' => 'name', 'placeholder' => trans('entities.pages_title')])
@@ -78,24 +78,24 @@
- Editor + {{ trans('entities.pages_md_editor') }}
- +  |  - +
+ @if($errors->has('markdown')) class="neg" @endif>@if(isset($model) || old('markdown')){{htmlspecialchars( old('markdown') ? old('markdown') : ($model->markdown === '' ? $model->html : $model->markdown))}}@endif
-
Preview
+
{{ trans('entities.pages_md_preview') }}
diff --git a/resources/views/pages/guest-create.blade.php b/resources/views/pages/guest-create.blade.php index 00d9f5560..10e16cb97 100644 --- a/resources/views/pages/guest-create.blade.php +++ b/resources/views/pages/guest-create.blade.php @@ -3,19 +3,19 @@ @section('content')
-

Create Page

+

{{ trans('entities.pages_new') }}

{!! csrf_field() !!}
- + @include('form/text', ['name' => 'name'])
- Cancel - + {{ trans('common.cancel') }} +
diff --git a/resources/views/pages/list-item.blade.php b/resources/views/pages/list-item.blade.php index 7aa5d7933..70b309e7d 100644 --- a/resources/views/pages/list-item.blade.php +++ b/resources/views/pages/list-item.blade.php @@ -12,8 +12,7 @@ @if(isset($style) && $style === 'detailed')
- Created {{$page->created_at->diffForHumans()}} @if($page->createdBy)by {{$page->createdBy->name}}@endif
- Last updated {{ $page->updated_at->diffForHumans() }} @if($page->updatedBy)by {{$page->updatedBy->name}} @endif + @include('partials.entity-meta', ['entity' => $page])
{{ $page->book->getShortName(30) }} @@ -21,7 +20,7 @@ @if($page->chapter) {{ $page->chapter->getShortName(30) }} @else - Page is not in a chapter + {{ trans('entities.pages_not_in_chapter') }} @endif
diff --git a/resources/views/pages/move.blade.php b/resources/views/pages/move.blade.php index d0fae60ca..a9b6d69d7 100644 --- a/resources/views/pages/move.blade.php +++ b/resources/views/pages/move.blade.php @@ -6,34 +6,23 @@
- + @include('pages._breadcrumbs', ['page' => $page])
-

Move Page {{$page->name}}

+

{{ trans('entities.pages_move') }}

{!! csrf_field() !!} - @include('partials/entity-selector', ['name' => 'entity_selection', 'selectorSize' => 'large', 'entityTypes' => 'book,chapter']) + @include('components.entity-selector', ['name' => 'entity_selection', 'selectorSize' => 'large', 'entityTypes' => 'book,chapter']) - Cancel - + {{ trans('common.cancel') }} +
diff --git a/resources/views/pages/page-display.blade.php b/resources/views/pages/page-display.blade.php index fb6ca3045..6eb927687 100644 --- a/resources/views/pages/page-display.blade.php +++ b/resources/views/pages/page-display.blade.php @@ -7,6 +7,6 @@ @if (isset($diff) && $diff) {!! $diff !!} @else - {!! $page->html !!} + {!! isset($pageContent) ? $pageContent : $page->html !!} @endif
\ No newline at end of file diff --git a/resources/views/pages/pdf.blade.php b/resources/views/pages/pdf.blade.php index 5c9fd5eea..7e43c5e1a 100644 --- a/resources/views/pages/pdf.blade.php +++ b/resources/views/pages/pdf.blade.php @@ -36,6 +36,5 @@ max-width: none; display: none; } - @stop \ No newline at end of file diff --git a/resources/views/pages/restrictions.blade.php b/resources/views/pages/restrictions.blade.php index bd88919df..cfef2ed21 100644 --- a/resources/views/pages/restrictions.blade.php +++ b/resources/views/pages/restrictions.blade.php @@ -6,26 +6,15 @@
- + @include('pages._breadcrumbs', ['page' => $page])
-

Page Permissions

- @include('form/restriction-form', ['model' => $page]) +

{{ trans('entities.pages_permissions') }}

+ @include('form.restriction-form', ['model' => $page])
@stop diff --git a/resources/views/pages/revision.blade.php b/resources/views/pages/revision.blade.php index bc054ef83..fe0dd9511 100644 --- a/resources/views/pages/revision.blade.php +++ b/resources/views/pages/revision.blade.php @@ -7,14 +7,12 @@
- @include('pages/page-display') + @include('pages.page-display')
- - @include('partials/highlight') - + @include('partials.highlight') @stop diff --git a/resources/views/pages/revisions.blade.php b/resources/views/pages/revisions.blade.php index 720e34fea..3b9812abd 100644 --- a/resources/views/pages/revisions.blade.php +++ b/resources/views/pages/revisions.blade.php @@ -6,37 +6,24 @@
- + @include('pages._breadcrumbs', ['page' => $page])
- -
-

Page Revisions For "{{ $page->name }}"

+

{{ trans('entities.pages_revisions') }}

@if(count($page->revisions) > 0) - - - - - + + + + + @foreach($page->revisions as $index => $revision) @@ -46,19 +33,19 @@ {{ $revision->createdBy->name }} @endif - + @@ -66,7 +53,7 @@
NameCreated ByRevision DateChangelogActions{{ trans('entities.pages_name') }}{{ trans('entities.pages_revisions_created_by') }}{{ trans('entities.pages_revisions_date') }}{{ trans('entities.pages_revisions_changelog') }}{{ trans('common.actions') }}
@if($revision->createdBy) {{ $revision->createdBy->name }} @else Deleted User @endif @if($revision->createdBy) {{ $revision->createdBy->name }} @else {{ trans('common.deleted_user') }} @endif {{ $revision->created_at->format('jS F, Y H:i:s') }}
({{ $revision->created_at->diffForHumans() }})
{{ $revision->summary }} - Changes + {{ trans('entities.pages_revisions_changes') }}  |  @if ($index === 0) - Current Version + {{ trans('entities.pages_revisions_current') }} @else - Preview + {{ trans('entities.pages_revisions_preview') }}  |  - Restore + {{ trans('entities.pages_revisions_restore') }} @endif
@else -

This page has no revisions.

+

{{ trans('entities.pages_revisions_none') }}

@endif
diff --git a/resources/views/pages/show.blade.php b/resources/views/pages/show.blade.php index 50c6f5d2c..fd6cebf41 100644 --- a/resources/views/pages/show.blade.php +++ b/resources/views/pages/show.blade.php @@ -6,43 +6,34 @@
- + @include('pages._breadcrumbs', ['page' => $page])
-
Export
+
{{ trans('entities.pages_export') }}
@if(userCan('page-update', $page)) - Edit + {{ trans('common.edit') }} @endif @if(userCan('page-update', $page) || userCan('restrictions-manage', $page) || userCan('page-delete', $page)) @@ -62,9 +53,9 @@
- - - + + +
@@ -72,11 +63,7 @@
-

- Created {{ $page->created_at->diffForHumans() }} @if($page->createdBy) by {{$page->createdBy->name}} @endif -
- Last Updated {{ $page->updated_at->diffForHumans() }} @if($page->updatedBy) by {{$page->updatedBy->name}} @endif -

+ @include('partials.entity-meta', ['entity' => $page])
@@ -88,27 +75,27 @@ @if($book->restricted) @if(userCan('restrictions-manage', $book)) - Book Permissions Active + {{ trans('entities.books_permissions_active') }} @else - Book Permissions Active + {{ trans('entities.books_permissions_active') }} @endif
@endif @if($page->chapter && $page->chapter->restricted) @if(userCan('restrictions-manage', $page->chapter)) - Chapter Permissions Active + {{ trans('entities.chapters_permissions_active') }} @else - Chapter Permissions Active + {{ trans('entities.chapters_permissions_active') }} @endif
@endif @if($page->restricted) @if(userCan('restrictions-manage', $page)) - Page Permissions Active + {{ trans('entities.pages_permissions_active') }} @else - Page Permissions Active + {{ trans('entities.pages_permissions_active') }} @endif
@endif diff --git a/resources/views/pages/sidebar-tree-list.blade.php b/resources/views/pages/sidebar-tree-list.blade.php index 5309cb774..f366e9e9b 100644 --- a/resources/views/pages/sidebar-tree-list.blade.php +++ b/resources/views/pages/sidebar-tree-list.blade.php @@ -18,26 +18,26 @@ @endif @if (isset($page) && $page->attachments->count() > 0) -
Attachments
+
{{ trans('entities.pages_attachments') }}
@foreach($page->attachments as $attachment) @endforeach @endif - @if (isset($pageNav) && $pageNav) -
Page Navigation
+ @if (isset($pageNav) && count($pageNav)) +
{{ trans('entities.pages_navigation') }}
@endif -
Book Navigation
+
{{ trans('entities.books_navigation') }}
@else -

No activity to show

+

{{ trans('common.no_activity') }}

@endif \ No newline at end of file diff --git a/resources/views/partials/custom-styles.blade.php b/resources/views/partials/custom-styles.blade.php index 885cc2729..62bcc881f 100644 --- a/resources/views/partials/custom-styles.blade.php +++ b/resources/views/partials/custom-styles.blade.php @@ -1,4 +1,4 @@ -