mirror of
https://github.com/BookStackApp/BookStack.git
synced 2025-08-09 10:22:51 +03:00
Entity Repo & Controller Refactor (#1690)
* Started mass-refactoring of the current entity repos * Rewrote book tree logic - Now does two simple queries instead of one really complex one. - Extracted logic into its own class. - Remove model-level akward union field listing. - Logic now more readable than being large separate query and compilation functions. * Extracted and split book sort logic * Finished up Book controller/repo organisation * Refactored bookshelves controllers and repo parts * Fixed issues found via phpunit * Refactored Chapter controller * Updated Chapter export controller * Started Page controller/repo refactor * Refactored another chunk of PageController * Completed initial pagecontroller refactor pass * Fixed tests and continued reduction of old repos * Removed old page remove and further reduced entity repo * Removed old entity repo, split out page controller * Ran phpcbf and split out some page content methods * Tidied up some EntityProvider elements * Fixed issued caused by viewservice change
This commit is contained in:
@@ -1,6 +1,11 @@
|
||||
<?php namespace BookStack\Entities;
|
||||
|
||||
use BookStack\Uploads\Image;
|
||||
use Exception;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* Class Book
|
||||
@@ -9,21 +14,12 @@ use BookStack\Uploads\Image;
|
||||
* @property Image|null $cover
|
||||
* @package BookStack\Entities
|
||||
*/
|
||||
class Book extends Entity
|
||||
class Book extends Entity implements HasCoverImage
|
||||
{
|
||||
public $searchFactor = 2;
|
||||
|
||||
protected $fillable = ['name', 'description', 'image_id'];
|
||||
|
||||
/**
|
||||
* Get the morph class for this model.
|
||||
* @return string
|
||||
*/
|
||||
public function getMorphClass()
|
||||
{
|
||||
return 'BookStack\\Book';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the url for this book.
|
||||
* @param string|bool $path
|
||||
@@ -52,7 +48,7 @@ class Book extends Entity
|
||||
|
||||
try {
|
||||
$cover = $this->cover ? url($this->cover->getThumb($width, $height, false)) : $default;
|
||||
} catch (\Exception $err) {
|
||||
} catch (Exception $err) {
|
||||
$cover = $default;
|
||||
}
|
||||
return $cover;
|
||||
@@ -60,16 +56,23 @@ class Book extends Entity
|
||||
|
||||
/**
|
||||
* Get the cover image of the book
|
||||
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
|
||||
*/
|
||||
public function cover()
|
||||
public function cover(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Image::class, 'image_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the type of the image model that is used when storing a cover image.
|
||||
*/
|
||||
public function coverImageTypeKey(): string
|
||||
{
|
||||
return 'cover_book';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all pages within this book.
|
||||
* @return \Illuminate\Database\Eloquent\Relations\HasMany
|
||||
* @return HasMany
|
||||
*/
|
||||
public function pages()
|
||||
{
|
||||
@@ -78,7 +81,7 @@ class Book extends Entity
|
||||
|
||||
/**
|
||||
* Get the direct child pages of this book.
|
||||
* @return \Illuminate\Database\Eloquent\Relations\HasMany
|
||||
* @return HasMany
|
||||
*/
|
||||
public function directPages()
|
||||
{
|
||||
@@ -87,7 +90,7 @@ class Book extends Entity
|
||||
|
||||
/**
|
||||
* Get all chapters within this book.
|
||||
* @return \Illuminate\Database\Eloquent\Relations\HasMany
|
||||
* @return HasMany
|
||||
*/
|
||||
public function chapters()
|
||||
{
|
||||
@@ -96,13 +99,24 @@ class Book extends Entity
|
||||
|
||||
/**
|
||||
* Get the shelves this book is contained within.
|
||||
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
|
||||
* @return BelongsToMany
|
||||
*/
|
||||
public function shelves()
|
||||
{
|
||||
return $this->belongsToMany(Bookshelf::class, 'bookshelves_books', 'book_id', 'bookshelf_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the direct child items within this book.
|
||||
* @return Collection
|
||||
*/
|
||||
public function getDirectChildren(): Collection
|
||||
{
|
||||
$pages = $this->directPages()->visible()->get();
|
||||
$chapters = $this->chapters()->visible()->get();
|
||||
return $pages->contact($chapters)->sortBy('priority')->sortByDesc('draft');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an excerpt of this book's description to the specified length or less.
|
||||
* @param int $length
|
||||
@@ -113,13 +127,4 @@ class Book extends Entity
|
||||
$description = $this->description;
|
||||
return mb_strlen($description) > $length ? mb_substr($description, 0, $length-3) . '...' : $description;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a generalised, common raw query that can be 'unioned' across entities.
|
||||
* @return string
|
||||
*/
|
||||
public function entityRawQuery()
|
||||
{
|
||||
return "'BookStack\\\\Book' as entity_type, id, id as entity_id, slug, name, {$this->textField} as text,'' as html, '0' as book_id, '0' as priority, '0' as chapter_id, '0' as draft, created_by, updated_by, updated_at, created_at";
|
||||
}
|
||||
}
|
||||
|
@@ -1,14 +1,31 @@
|
||||
<?php namespace BookStack\Entities;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Class BookChild
|
||||
* @property int $book_id
|
||||
* @property int $priority
|
||||
* @property Book $book
|
||||
* @method Builder whereSlugs(string $bookSlug, string $childSlug)
|
||||
*/
|
||||
class BookChild extends Entity
|
||||
{
|
||||
|
||||
/**
|
||||
* Scope a query to find items where the the child has the given childSlug
|
||||
* where its parent has the bookSlug.
|
||||
*/
|
||||
public function scopeWhereSlugs(Builder $query, string $bookSlug, string $childSlug)
|
||||
{
|
||||
return $query->with('book')
|
||||
->whereHas('book', function (Builder $query) use ($bookSlug) {
|
||||
$query->where('slug', '=', $bookSlug);
|
||||
})
|
||||
->where('slug', '=', $childSlug);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the book this page sits in.
|
||||
* @return BelongsTo
|
||||
@@ -18,4 +35,26 @@ class BookChild extends Entity
|
||||
return $this->belongsTo(Book::class);
|
||||
}
|
||||
|
||||
}
|
||||
/**
|
||||
* Change the book that this entity belongs to.
|
||||
*/
|
||||
public function changeBook(int $newBookId): Entity
|
||||
{
|
||||
$this->book_id = $newBookId;
|
||||
$this->refreshSlug();
|
||||
$this->save();
|
||||
$this->refresh();
|
||||
|
||||
// Update related activity
|
||||
$this->activity()->update(['book_id' => $newBookId]);
|
||||
|
||||
// Update all child pages if a chapter
|
||||
if ($this instanceof Chapter) {
|
||||
foreach ($this->pages as $page) {
|
||||
$page->changeBook($newBookId);
|
||||
}
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
|
@@ -1,8 +1,10 @@
|
||||
<?php namespace BookStack\Entities;
|
||||
|
||||
use BookStack\Uploads\Image;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
|
||||
class Bookshelf extends Entity
|
||||
class Bookshelf extends Entity implements HasCoverImage
|
||||
{
|
||||
protected $table = 'bookshelves';
|
||||
|
||||
@@ -10,15 +12,6 @@ class Bookshelf extends Entity
|
||||
|
||||
protected $fillable = ['name', 'description', 'image_id'];
|
||||
|
||||
/**
|
||||
* Get the morph class for this model.
|
||||
* @return string
|
||||
*/
|
||||
public function getMorphClass()
|
||||
{
|
||||
return 'BookStack\\Bookshelf';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the books in this shelf.
|
||||
* Should not be used directly since does not take into account permissions.
|
||||
@@ -31,6 +24,14 @@ class Bookshelf extends Entity
|
||||
->orderBy('order', 'asc');
|
||||
}
|
||||
|
||||
/**
|
||||
* Related books that are visible to the current user.
|
||||
*/
|
||||
public function visibleBooks(): BelongsToMany
|
||||
{
|
||||
return $this->books()->visible();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the url for this bookshelf.
|
||||
* @param string|bool $path
|
||||
@@ -68,13 +69,20 @@ class Bookshelf extends Entity
|
||||
|
||||
/**
|
||||
* Get the cover image of the shelf
|
||||
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
|
||||
*/
|
||||
public function cover()
|
||||
public function cover(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Image::class, 'image_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the type of the image model that is used when storing a cover image.
|
||||
*/
|
||||
public function coverImageTypeKey(): string
|
||||
{
|
||||
return 'cover_shelf';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an excerpt of this book's description to the specified length or less.
|
||||
* @param int $length
|
||||
@@ -86,21 +94,12 @@ class Bookshelf extends Entity
|
||||
return mb_strlen($description) > $length ? mb_substr($description, 0, $length-3) . '...' : $description;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a generalised, common raw query that can be 'unioned' across entities.
|
||||
* @return string
|
||||
*/
|
||||
public function entityRawQuery()
|
||||
{
|
||||
return "'BookStack\\\\BookShelf' as entity_type, id, id as entity_id, slug, name, {$this->textField} as text,'' as html, '0' as book_id, '0' as priority, '0' as chapter_id, '0' as draft, created_by, updated_by, updated_at, created_at";
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this shelf contains the given book.
|
||||
* @param Book $book
|
||||
* @return bool
|
||||
*/
|
||||
public function contains(Book $book): bool
|
||||
public function contains(Book $book): bool
|
||||
{
|
||||
return $this->books()->where('id', '=', $book->id)->count() > 0;
|
||||
}
|
||||
@@ -111,11 +110,11 @@ class Bookshelf extends Entity
|
||||
*/
|
||||
public function appendBook(Book $book)
|
||||
{
|
||||
if ($this->contains($book)) {
|
||||
return;
|
||||
}
|
||||
if ($this->contains($book)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$maxOrder = $this->books()->max('order');
|
||||
$this->books()->attach($book->id, ['order' => $maxOrder + 1]);
|
||||
$maxOrder = $this->books()->max('order');
|
||||
$this->books()->attach($book->id, ['order' => $maxOrder + 1]);
|
||||
}
|
||||
}
|
||||
|
@@ -1,5 +1,6 @@
|
||||
<?php namespace BookStack\Entities;
|
||||
|
||||
use BookStack\Entities\Managers\EntityContext;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class BreadcrumbsViewComposer
|
||||
@@ -9,9 +10,9 @@ class BreadcrumbsViewComposer
|
||||
|
||||
/**
|
||||
* BreadcrumbsViewComposer constructor.
|
||||
* @param EntityContextManager $entityContextManager
|
||||
* @param EntityContext $entityContextManager
|
||||
*/
|
||||
public function __construct(EntityContextManager $entityContextManager)
|
||||
public function __construct(EntityContext $entityContextManager)
|
||||
{
|
||||
$this->entityContextManager = $entityContextManager;
|
||||
}
|
||||
|
@@ -1,22 +1,18 @@
|
||||
<?php namespace BookStack\Entities;
|
||||
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* Class Chapter
|
||||
* @property Collection<Page> $pages
|
||||
* @package BookStack\Entities
|
||||
*/
|
||||
class Chapter extends BookChild
|
||||
{
|
||||
public $searchFactor = 1.3;
|
||||
|
||||
protected $fillable = ['name', 'description', 'priority', 'book_id'];
|
||||
|
||||
/**
|
||||
* Get the morph class for this model.
|
||||
* @return string
|
||||
*/
|
||||
public function getMorphClass()
|
||||
{
|
||||
return 'BookStack\\Chapter';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the pages that this chapter contains.
|
||||
* @param string $dir
|
||||
@@ -55,15 +51,6 @@ class Chapter extends BookChild
|
||||
return mb_strlen($description) > $length ? mb_substr($description, 0, $length-3) . '...' : $description;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a generalised, common raw query that can be 'unioned' across entities.
|
||||
* @return string
|
||||
*/
|
||||
public function entityRawQuery()
|
||||
{
|
||||
return "'BookStack\\\\Chapter' as entity_type, id, id as entity_id, slug, name, {$this->textField} as text, '' as html, book_id, priority, '0' as chapter_id, '0' as draft, created_by, updated_by, updated_at, created_at";
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this chapter has any child pages.
|
||||
* @return bool
|
||||
@@ -72,4 +59,15 @@ class Chapter extends BookChild
|
||||
{
|
||||
return count($this->pages) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the visible pages in this chapter.
|
||||
*/
|
||||
public function getVisiblePages(): Collection
|
||||
{
|
||||
return $this->pages()->visible()
|
||||
->orderBy('draft', 'desc')
|
||||
->orderBy('priority', 'asc')
|
||||
->get();
|
||||
}
|
||||
}
|
||||
|
@@ -9,6 +9,8 @@ use BookStack\Auth\Permissions\JointPermission;
|
||||
use BookStack\Facades\Permissions;
|
||||
use BookStack\Ownable;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Database\Eloquent\Relations\MorphMany;
|
||||
|
||||
/**
|
||||
@@ -24,6 +26,11 @@ use Illuminate\Database\Eloquent\Relations\MorphMany;
|
||||
* @property int $created_by
|
||||
* @property int $updated_by
|
||||
* @property boolean $restricted
|
||||
* @property Collection $tags
|
||||
* @method static Entity|Builder visible()
|
||||
* @method static Entity|Builder hasPermission(string $permission)
|
||||
* @method static Builder withLastView()
|
||||
* @method static Builder withViewCount()
|
||||
*
|
||||
* @package BookStack\Entities
|
||||
*/
|
||||
@@ -41,14 +48,45 @@ class Entity extends Ownable
|
||||
public $searchFactor = 1.0;
|
||||
|
||||
/**
|
||||
* Get the morph class for this model.
|
||||
* Set here since, due to folder changes, the namespace used
|
||||
* in the database no longer matches the class namespace.
|
||||
* @return string
|
||||
* Get the entities that are visible to the current user.
|
||||
*/
|
||||
public function getMorphClass()
|
||||
public function scopeVisible(Builder $query)
|
||||
{
|
||||
return 'BookStack\\Entity';
|
||||
return $this->scopeHasPermission($query, 'view');
|
||||
}
|
||||
|
||||
/**
|
||||
* Scope the query to those entities that the current user has the given permission for.
|
||||
*/
|
||||
public function scopeHasPermission(Builder $query, string $permission)
|
||||
{
|
||||
return Permissions::restrictEntityQuery($query, $permission);
|
||||
}
|
||||
|
||||
/**
|
||||
* Query scope to get the last view from the current user.
|
||||
*/
|
||||
public function scopeWithLastView(Builder $query)
|
||||
{
|
||||
$viewedAtQuery = View::query()->select('updated_at')
|
||||
->whereColumn('viewable_id', '=', $this->getTable() . '.id')
|
||||
->where('viewable_type', '=', $this->getMorphClass())
|
||||
->where('user_id', '=', user()->id)
|
||||
->take(1);
|
||||
|
||||
return $query->addSelect(['last_viewed_at' => $viewedAtQuery]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Query scope to get the total view count of the entities.
|
||||
*/
|
||||
public function scopeWithViewCount(Builder $query)
|
||||
{
|
||||
$viewCountQuery = View::query()->selectRaw('SUM(views) as view_count')
|
||||
->whereColumn('viewable_id', '=', $this->getTable() . '.id')
|
||||
->where('viewable_type', '=', $this->getMorphClass())->take(1);
|
||||
|
||||
$query->addSelect(['view_count' => $viewCountQuery]);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -88,7 +126,7 @@ class Entity extends Ownable
|
||||
|
||||
/**
|
||||
* Gets the activity objects for this entity.
|
||||
* @return \Illuminate\Database\Eloquent\Relations\MorphMany
|
||||
* @return MorphMany
|
||||
*/
|
||||
public function activity()
|
||||
{
|
||||
@@ -106,7 +144,7 @@ class Entity extends Ownable
|
||||
|
||||
/**
|
||||
* Get the Tag models that have been user assigned to this entity.
|
||||
* @return \Illuminate\Database\Eloquent\Relations\MorphMany
|
||||
* @return MorphMany
|
||||
*/
|
||||
public function tags()
|
||||
{
|
||||
@@ -126,7 +164,7 @@ class Entity extends Ownable
|
||||
|
||||
/**
|
||||
* Get the related search terms.
|
||||
* @return \Illuminate\Database\Eloquent\Relations\MorphMany
|
||||
* @return MorphMany
|
||||
*/
|
||||
public function searchTerms()
|
||||
{
|
||||
@@ -155,7 +193,7 @@ class Entity extends Ownable
|
||||
|
||||
/**
|
||||
* Get the entity jointPermissions this is connected to.
|
||||
* @return \Illuminate\Database\Eloquent\Relations\MorphMany
|
||||
* @return MorphMany
|
||||
*/
|
||||
public function jointPermissions()
|
||||
{
|
||||
@@ -182,14 +220,6 @@ class Entity extends Ownable
|
||||
return strtolower(static::getClassName());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the type of this entity.
|
||||
*/
|
||||
public function type(): string
|
||||
{
|
||||
return static::getType();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an instance of an entity of the given type.
|
||||
* @param $type
|
||||
@@ -242,15 +272,6 @@ class Entity extends Ownable
|
||||
return trim($text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a generalised, common raw query that can be 'unioned' across entities.
|
||||
* @return string
|
||||
*/
|
||||
public function entityRawQuery()
|
||||
{
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the url of this entity
|
||||
* @param $path
|
||||
@@ -270,6 +291,15 @@ class Entity extends Ownable
|
||||
Permissions::buildJointPermissionsForEntity($this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Index the current entity for search
|
||||
*/
|
||||
public function indexForSearch()
|
||||
{
|
||||
$searchService = app()->make(SearchService::class);
|
||||
$searchService->indexEntity($this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate and set a new URL slug for this model.
|
||||
*/
|
||||
|
@@ -39,11 +39,6 @@ class EntityProvider
|
||||
|
||||
/**
|
||||
* EntityProvider constructor.
|
||||
* @param Bookshelf $bookshelf
|
||||
* @param Book $book
|
||||
* @param Chapter $chapter
|
||||
* @param Page $page
|
||||
* @param PageRevision $pageRevision
|
||||
*/
|
||||
public function __construct(
|
||||
Bookshelf $bookshelf,
|
||||
@@ -62,9 +57,8 @@ class EntityProvider
|
||||
/**
|
||||
* Fetch all core entity types as an associated array
|
||||
* with their basic names as the keys.
|
||||
* @return Entity[]
|
||||
*/
|
||||
public function all()
|
||||
public function all(): array
|
||||
{
|
||||
return [
|
||||
'bookshelf' => $this->bookshelf,
|
||||
@@ -76,10 +70,8 @@ class EntityProvider
|
||||
|
||||
/**
|
||||
* Get an entity instance by it's basic name.
|
||||
* @param string $type
|
||||
* @return Entity
|
||||
*/
|
||||
public function get(string $type)
|
||||
public function get(string $type): Entity
|
||||
{
|
||||
$type = strtolower($type);
|
||||
return $this->all()[$type];
|
||||
@@ -87,15 +79,9 @@ class EntityProvider
|
||||
|
||||
/**
|
||||
* Get the morph classes, as an array, for a single or multiple types.
|
||||
* @param string|array $types
|
||||
* @return array<string>
|
||||
*/
|
||||
public function getMorphClasses($types)
|
||||
public function getMorphClasses(array $types): array
|
||||
{
|
||||
if (is_string($types)) {
|
||||
$types = [$types];
|
||||
}
|
||||
|
||||
$morphClasses = [];
|
||||
foreach ($types as $type) {
|
||||
$model = $this->get($type);
|
||||
|
@@ -1,35 +1,34 @@
|
||||
<?php namespace BookStack\Entities;
|
||||
|
||||
use BookStack\Entities\Repos\EntityRepo;
|
||||
use BookStack\Entities\Managers\BookContents;
|
||||
use BookStack\Entities\Managers\PageContent;
|
||||
use BookStack\Uploads\ImageService;
|
||||
use DomPDF;
|
||||
use Exception;
|
||||
use SnappyPDF;
|
||||
use Throwable;
|
||||
|
||||
class ExportService
|
||||
{
|
||||
|
||||
protected $entityRepo;
|
||||
protected $imageService;
|
||||
|
||||
/**
|
||||
* ExportService constructor.
|
||||
* @param EntityRepo $entityRepo
|
||||
* @param ImageService $imageService
|
||||
*/
|
||||
public function __construct(EntityRepo $entityRepo, ImageService $imageService)
|
||||
public function __construct(ImageService $imageService)
|
||||
{
|
||||
$this->entityRepo = $entityRepo;
|
||||
$this->imageService = $imageService;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a page to a self-contained HTML file.
|
||||
* Includes required CSS & image content. Images are base64 encoded into the HTML.
|
||||
* @param \BookStack\Entities\Page $page
|
||||
* @return mixed|string
|
||||
* @throws \Throwable
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function pageToContainedHtml(Page $page)
|
||||
{
|
||||
$this->entityRepo->renderPage($page);
|
||||
$page->html = (new PageContent($page))->render();
|
||||
$pageHtml = view('pages/export', [
|
||||
'page' => $page
|
||||
])->render();
|
||||
@@ -38,15 +37,13 @@ class ExportService
|
||||
|
||||
/**
|
||||
* Convert a chapter to a self-contained HTML file.
|
||||
* @param \BookStack\Entities\Chapter $chapter
|
||||
* @return mixed|string
|
||||
* @throws \Throwable
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function chapterToContainedHtml(Chapter $chapter)
|
||||
{
|
||||
$pages = $this->entityRepo->getChapterChildren($chapter);
|
||||
$pages = $chapter->getVisiblePages();
|
||||
$pages->each(function ($page) {
|
||||
$page->html = $this->entityRepo->renderPage($page);
|
||||
$page->html = (new PageContent($page))->render();
|
||||
});
|
||||
$html = view('chapters/export', [
|
||||
'chapter' => $chapter,
|
||||
@@ -57,13 +54,11 @@ class ExportService
|
||||
|
||||
/**
|
||||
* Convert a book to a self-contained HTML file.
|
||||
* @param Book $book
|
||||
* @return mixed|string
|
||||
* @throws \Throwable
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function bookToContainedHtml(Book $book)
|
||||
{
|
||||
$bookTree = $this->entityRepo->getBookChildren($book, true, true);
|
||||
$bookTree = (new BookContents($book))->getTree(false, true);
|
||||
$html = view('books/export', [
|
||||
'book' => $book,
|
||||
'bookChildren' => $bookTree
|
||||
@@ -73,13 +68,11 @@ class ExportService
|
||||
|
||||
/**
|
||||
* Convert a page to a PDF file.
|
||||
* @param Page $page
|
||||
* @return mixed|string
|
||||
* @throws \Throwable
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function pageToPdf(Page $page)
|
||||
{
|
||||
$this->entityRepo->renderPage($page);
|
||||
$page->html = (new PageContent($page))->render();
|
||||
$html = view('pages/pdf', [
|
||||
'page' => $page
|
||||
])->render();
|
||||
@@ -88,32 +81,30 @@ class ExportService
|
||||
|
||||
/**
|
||||
* Convert a chapter to a PDF file.
|
||||
* @param \BookStack\Entities\Chapter $chapter
|
||||
* @return mixed|string
|
||||
* @throws \Throwable
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function chapterToPdf(Chapter $chapter)
|
||||
{
|
||||
$pages = $this->entityRepo->getChapterChildren($chapter);
|
||||
$pages = $chapter->getVisiblePages();
|
||||
$pages->each(function ($page) {
|
||||
$page->html = $this->entityRepo->renderPage($page);
|
||||
$page->html = (new PageContent($page))->render();
|
||||
});
|
||||
|
||||
$html = view('chapters/export', [
|
||||
'chapter' => $chapter,
|
||||
'pages' => $pages
|
||||
])->render();
|
||||
|
||||
return $this->htmlToPdf($html);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a book to a PDF file
|
||||
* @param \BookStack\Entities\Book $book
|
||||
* @return string
|
||||
* @throws \Throwable
|
||||
* Convert a book to a PDF file.
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function bookToPdf(Book $book)
|
||||
{
|
||||
$bookTree = $this->entityRepo->getBookChildren($book, true, true);
|
||||
$bookTree = (new BookContents($book))->getTree(false, true);
|
||||
$html = view('books/export', [
|
||||
'book' => $book,
|
||||
'bookChildren' => $bookTree
|
||||
@@ -122,31 +113,27 @@ class ExportService
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert normal webpage HTML to a PDF.
|
||||
* @param $html
|
||||
* @return string
|
||||
* @throws \Exception
|
||||
* Convert normal web-page HTML to a PDF.
|
||||
* @throws Exception
|
||||
*/
|
||||
protected function htmlToPdf($html)
|
||||
protected function htmlToPdf(string $html): string
|
||||
{
|
||||
$containedHtml = $this->containHtml($html);
|
||||
$useWKHTML = config('snappy.pdf.binary') !== false;
|
||||
if ($useWKHTML) {
|
||||
$pdf = \SnappyPDF::loadHTML($containedHtml);
|
||||
$pdf = SnappyPDF::loadHTML($containedHtml);
|
||||
$pdf->setOption('print-media-type', true);
|
||||
} else {
|
||||
$pdf = \DomPDF::loadHTML($containedHtml);
|
||||
$pdf = DomPDF::loadHTML($containedHtml);
|
||||
}
|
||||
return $pdf->output();
|
||||
}
|
||||
|
||||
/**
|
||||
* Bundle of the contents of a html file to be self-contained.
|
||||
* @param $htmlContent
|
||||
* @return mixed|string
|
||||
* @throws \Exception
|
||||
* @throws Exception
|
||||
*/
|
||||
protected function containHtml($htmlContent)
|
||||
protected function containHtml(string $htmlContent): string
|
||||
{
|
||||
$imageTagsOutput = [];
|
||||
preg_match_all("/\<img.*src\=(\'|\")(.*?)(\'|\").*?\>/i", $htmlContent, $imageTagsOutput);
|
||||
@@ -188,12 +175,10 @@ class ExportService
|
||||
/**
|
||||
* Converts the page contents into simple plain text.
|
||||
* This method filters any bad looking content to provide a nice final output.
|
||||
* @param Page $page
|
||||
* @return mixed
|
||||
*/
|
||||
public function pageToPlainText(Page $page)
|
||||
public function pageToPlainText(Page $page): string
|
||||
{
|
||||
$html = $this->entityRepo->renderPage($page);
|
||||
$html = (new PageContent($page))->render();
|
||||
$text = strip_tags($html);
|
||||
// Replace multiple spaces with single spaces
|
||||
$text = preg_replace('/\ {2,}/', ' ', $text);
|
||||
@@ -207,10 +192,8 @@ class ExportService
|
||||
|
||||
/**
|
||||
* Convert a chapter into a plain text string.
|
||||
* @param \BookStack\Entities\Chapter $chapter
|
||||
* @return string
|
||||
*/
|
||||
public function chapterToPlainText(Chapter $chapter)
|
||||
public function chapterToPlainText(Chapter $chapter): string
|
||||
{
|
||||
$text = $chapter->name . "\n\n";
|
||||
$text .= $chapter->description . "\n\n";
|
||||
@@ -222,12 +205,10 @@ class ExportService
|
||||
|
||||
/**
|
||||
* Convert a book into a plain text string.
|
||||
* @param Book $book
|
||||
* @return string
|
||||
*/
|
||||
public function bookToPlainText(Book $book)
|
||||
public function bookToPlainText(Book $book): string
|
||||
{
|
||||
$bookTree = $this->entityRepo->getBookChildren($book, true, true);
|
||||
$bookTree = (new BookContents($book))->getTree(false, true);
|
||||
$text = $book->name . "\n\n";
|
||||
foreach ($bookTree as $bookChild) {
|
||||
if ($bookChild->isA('chapter')) {
|
||||
|
20
app/Entities/HasCoverImage.php
Normal file
20
app/Entities/HasCoverImage.php
Normal file
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace BookStack\Entities;
|
||||
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
interface HasCoverImage
|
||||
{
|
||||
|
||||
/**
|
||||
* Get the cover image for this item.
|
||||
*/
|
||||
public function cover(): BelongsTo;
|
||||
|
||||
/**
|
||||
* Get the type of the image model that is used when storing a cover image.
|
||||
*/
|
||||
public function coverImageTypeKey(): string;
|
||||
}
|
204
app/Entities/Managers/BookContents.php
Normal file
204
app/Entities/Managers/BookContents.php
Normal file
@@ -0,0 +1,204 @@
|
||||
<?php namespace BookStack\Entities\Managers;
|
||||
|
||||
use BookStack\Entities\Book;
|
||||
use BookStack\Entities\BookChild;
|
||||
use BookStack\Entities\Chapter;
|
||||
use BookStack\Entities\Entity;
|
||||
use BookStack\Entities\Page;
|
||||
use BookStack\Exceptions\SortOperationException;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class BookContents
|
||||
{
|
||||
|
||||
/**
|
||||
* @var Book
|
||||
*/
|
||||
protected $book;
|
||||
|
||||
/**
|
||||
* BookContents constructor.
|
||||
* @param $book
|
||||
*/
|
||||
public function __construct(Book $book)
|
||||
{
|
||||
$this->book = $book;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current priority of the last item
|
||||
* at the top-level of the book.
|
||||
*/
|
||||
public function getLastPriority(): int
|
||||
{
|
||||
$maxPage = Page::visible()->where('book_id', '=', $this->book->id)
|
||||
->where('draft', '=', false)
|
||||
->where('chapter_id', '=', 0)->max('priority');
|
||||
$maxChapter = Chapter::visible()->where('book_id', '=', $this->book->id)
|
||||
->max('priority');
|
||||
return max($maxChapter, $maxPage, 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the contents as a sorted collection tree.
|
||||
* TODO - Support $renderPages option
|
||||
*/
|
||||
public function getTree(bool $showDrafts = false, bool $renderPages = false): Collection
|
||||
{
|
||||
$pages = $this->getPages($showDrafts);
|
||||
$chapters = Chapter::visible()->where('book_id', '=', $this->book->id)->get();
|
||||
$all = collect()->concat($pages)->concat($chapters);
|
||||
$chapterMap = $chapters->keyBy('id');
|
||||
$lonePages = collect();
|
||||
|
||||
$pages->groupBy('chapter_id')->each(function ($pages, $chapter_id) use ($chapterMap, &$lonePages) {
|
||||
$chapter = $chapterMap->get($chapter_id);
|
||||
if ($chapter) {
|
||||
$chapter->setAttribute('pages', collect($pages)->sortBy($this->bookChildSortFunc()));
|
||||
} else {
|
||||
$lonePages = $lonePages->concat($pages);
|
||||
}
|
||||
});
|
||||
|
||||
$all->each(function (Entity $entity) {
|
||||
$entity->setRelation('book', $this->book);
|
||||
});
|
||||
|
||||
return collect($chapters)->concat($lonePages)->sortBy($this->bookChildSortFunc());
|
||||
}
|
||||
|
||||
/**
|
||||
* Function for providing a sorting score for an entity in relation to the
|
||||
* other items within the book.
|
||||
*/
|
||||
protected function bookChildSortFunc(): callable
|
||||
{
|
||||
return function (Entity $entity) {
|
||||
if (isset($entity['draft']) && $entity['draft']) {
|
||||
return -100;
|
||||
}
|
||||
return $entity['priority'] ?? 0;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the visible pages within this book.
|
||||
*/
|
||||
protected function getPages(bool $showDrafts = false): Collection
|
||||
{
|
||||
$query = Page::visible()->where('book_id', '=', $this->book->id);
|
||||
|
||||
if (!$showDrafts) {
|
||||
$query->where('draft', '=', false);
|
||||
}
|
||||
|
||||
return $query->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort the books content using the given map.
|
||||
* The map is a single-dimension collection of objects in the following format:
|
||||
* {
|
||||
* +"id": "294" (ID of item)
|
||||
* +"sort": 1 (Sort order index)
|
||||
* +"parentChapter": false (ID of parent chapter, as string, or false)
|
||||
* +"type": "page" (Entity type of item)
|
||||
* +"book": "1" (Id of book to place item in)
|
||||
* }
|
||||
*
|
||||
* Returns a list of books that were involved in the operation.
|
||||
* @throws SortOperationException
|
||||
*/
|
||||
public function sortUsingMap(Collection $sortMap): Collection
|
||||
{
|
||||
// Load models into map
|
||||
$this->loadModelsIntoSortMap($sortMap);
|
||||
$booksInvolved = $this->getBooksInvolvedInSort($sortMap);
|
||||
|
||||
// Perform the sort
|
||||
$sortMap->each(function ($mapItem) {
|
||||
$this->applySortUpdates($mapItem);
|
||||
});
|
||||
|
||||
// Update permissions and activity.
|
||||
$booksInvolved->each(function (Book $book) {
|
||||
$book->rebuildPermissions();
|
||||
});
|
||||
|
||||
return $booksInvolved;
|
||||
}
|
||||
|
||||
/**
|
||||
* Using the given sort map item, detect changes for the related model
|
||||
* and update it if required.
|
||||
*/
|
||||
protected function applySortUpdates(\stdClass $sortMapItem)
|
||||
{
|
||||
/** @var BookChild $model */
|
||||
$model = $sortMapItem->model;
|
||||
|
||||
$priorityChanged = intval($model->priority) !== intval($sortMapItem->sort);
|
||||
$bookChanged = intval($model->book_id) !== intval($sortMapItem->book);
|
||||
$chapterChanged = ($sortMapItem->type === 'page') && intval($model->chapter_id) !== $sortMapItem->parentChapter;
|
||||
|
||||
if ($bookChanged) {
|
||||
$model->changeBook($sortMapItem->book);
|
||||
}
|
||||
|
||||
if ($chapterChanged) {
|
||||
$model->chapter_id = intval($sortMapItem->parentChapter);
|
||||
$model->save();
|
||||
}
|
||||
|
||||
if ($priorityChanged) {
|
||||
$model->priority = intval($sortMapItem->sort);
|
||||
$model->save();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load models from the database into the given sort map.
|
||||
*/
|
||||
protected function loadModelsIntoSortMap(Collection $sortMap): void
|
||||
{
|
||||
$keyMap = $sortMap->keyBy(function (\stdClass $sortMapItem) {
|
||||
return $sortMapItem->type . ':' . $sortMapItem->id;
|
||||
});
|
||||
$pageIds = $sortMap->where('type', '=', 'page')->pluck('id');
|
||||
$chapterIds = $sortMap->where('type', '=', 'chapter')->pluck('id');
|
||||
|
||||
$pages = Page::visible()->whereIn('id', $pageIds)->get();
|
||||
$chapters = Chapter::visible()->whereIn('id', $chapterIds)->get();
|
||||
|
||||
foreach ($pages as $page) {
|
||||
$sortItem = $keyMap->get('page:' . $page->id);
|
||||
$sortItem->model = $page;
|
||||
}
|
||||
|
||||
foreach ($chapters as $chapter) {
|
||||
$sortItem = $keyMap->get('chapter:' . $chapter->id);
|
||||
$sortItem->model = $chapter;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the books involved in a sort.
|
||||
* The given sort map should have its models loaded first.
|
||||
* @throws SortOperationException
|
||||
*/
|
||||
protected function getBooksInvolvedInSort(Collection $sortMap): Collection
|
||||
{
|
||||
$bookIdsInvolved = collect([$this->book->id]);
|
||||
$bookIdsInvolved = $bookIdsInvolved->concat($sortMap->pluck('book'));
|
||||
$bookIdsInvolved = $bookIdsInvolved->concat($sortMap->pluck('model.book_id'));
|
||||
$bookIdsInvolved = $bookIdsInvolved->unique()->toArray();
|
||||
|
||||
$books = Book::hasPermission('update')->whereIn('id', $bookIdsInvolved)->get();
|
||||
|
||||
if (count($books) !== count($bookIdsInvolved)) {
|
||||
throw new SortOperationException("Could not find all books requested in sort operation");
|
||||
}
|
||||
|
||||
return $books;
|
||||
}
|
||||
}
|
@@ -1,44 +1,38 @@
|
||||
<?php namespace BookStack\Entities;
|
||||
<?php namespace BookStack\Entities\Managers;
|
||||
|
||||
use BookStack\Entities\Repos\EntityRepo;
|
||||
use BookStack\Entities\Book;
|
||||
use BookStack\Entities\Bookshelf;
|
||||
use Illuminate\Session\Store;
|
||||
|
||||
class EntityContextManager
|
||||
class EntityContext
|
||||
{
|
||||
protected $session;
|
||||
protected $entityRepo;
|
||||
|
||||
protected $KEY_SHELF_CONTEXT_ID = 'context_bookshelf_id';
|
||||
|
||||
/**
|
||||
* EntityContextManager constructor.
|
||||
* @param Store $session
|
||||
* @param EntityRepo $entityRepo
|
||||
*/
|
||||
public function __construct(Store $session, EntityRepo $entityRepo)
|
||||
public function __construct(Store $session)
|
||||
{
|
||||
$this->session = $session;
|
||||
$this->entityRepo = $entityRepo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current bookshelf context for the given book.
|
||||
* @param Book $book
|
||||
* @return Bookshelf|null
|
||||
*/
|
||||
public function getContextualShelfForBook(Book $book)
|
||||
public function getContextualShelfForBook(Book $book): ?Bookshelf
|
||||
{
|
||||
$contextBookshelfId = $this->session->get($this->KEY_SHELF_CONTEXT_ID, null);
|
||||
if (is_int($contextBookshelfId)) {
|
||||
|
||||
/** @var Bookshelf $shelf */
|
||||
$shelf = $this->entityRepo->getById('bookshelf', $contextBookshelfId);
|
||||
|
||||
if ($shelf && $shelf->contains($book)) {
|
||||
return $shelf;
|
||||
}
|
||||
if (!is_int($contextBookshelfId)) {
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
|
||||
$shelf = Bookshelf::visible()->find($contextBookshelfId);
|
||||
$shelfContainsBook = $shelf && $shelf->contains($book);
|
||||
|
||||
return $shelfContainsBook ? $shelf : null;
|
||||
}
|
||||
|
||||
/**
|
304
app/Entities/Managers/PageContent.php
Normal file
304
app/Entities/Managers/PageContent.php
Normal file
@@ -0,0 +1,304 @@
|
||||
<?php namespace BookStack\Entities\Managers;
|
||||
|
||||
use BookStack\Entities\Page;
|
||||
use DOMDocument;
|
||||
use DOMElement;
|
||||
use DOMNodeList;
|
||||
use DOMXPath;
|
||||
|
||||
class PageContent
|
||||
{
|
||||
|
||||
protected $page;
|
||||
|
||||
/**
|
||||
* PageContent constructor.
|
||||
*/
|
||||
public function __construct(Page $page)
|
||||
{
|
||||
$this->page = $page;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the content of the page with new provided HTML.
|
||||
*/
|
||||
public function setNewHTML(string $html)
|
||||
{
|
||||
$this->page->html = $this->formatHtml($html);
|
||||
$this->page->text = $this->toPlainText();
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats a page's html to be tagged correctly within the system.
|
||||
*/
|
||||
protected function formatHtml(string $htmlText): string
|
||||
{
|
||||
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;
|
||||
|
||||
// Set ids on top-level nodes
|
||||
$idMap = [];
|
||||
foreach ($childNodes as $index => $childNode) {
|
||||
$this->setUniqueId($childNode, $idMap);
|
||||
}
|
||||
|
||||
// Ensure no duplicate ids within child items
|
||||
$xPath = new DOMXPath($doc);
|
||||
$idElems = $xPath->query('//body//*//*[@id]');
|
||||
foreach ($idElems as $domElem) {
|
||||
$this->setUniqueId($domElem, $idMap);
|
||||
}
|
||||
|
||||
// Generate inner html as a string
|
||||
$html = '';
|
||||
foreach ($childNodes as $childNode) {
|
||||
$html .= $doc->saveHTML($childNode);
|
||||
}
|
||||
|
||||
return $html;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a unique id on the given DOMElement.
|
||||
* A map for existing ID's should be passed in to check for current existence.
|
||||
* @param DOMElement $element
|
||||
* @param array $idMap
|
||||
*/
|
||||
protected function setUniqueId($element, array &$idMap)
|
||||
{
|
||||
if (get_class($element) !== 'DOMElement') {
|
||||
return;
|
||||
}
|
||||
|
||||
// Overwrite id if not a BookStack custom id
|
||||
$existingId = $element->getAttribute('id');
|
||||
if (strpos($existingId, 'bkmrk') === 0 && !isset($idMap[$existingId])) {
|
||||
$idMap[$existingId] = true;
|
||||
return;
|
||||
}
|
||||
|
||||
// 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-' . mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20);
|
||||
$newId = urlencode($contentId);
|
||||
$loopIndex = 0;
|
||||
|
||||
while (isset($idMap[$newId])) {
|
||||
$newId = urlencode($contentId . '-' . $loopIndex);
|
||||
$loopIndex++;
|
||||
}
|
||||
|
||||
$element->setAttribute('id', $newId);
|
||||
$idMap[$newId] = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a plain-text visualisation of this page.
|
||||
*/
|
||||
protected function toPlainText(): string
|
||||
{
|
||||
$html = $this->render(true);
|
||||
return strip_tags($html);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the page for viewing
|
||||
*/
|
||||
public function render(bool $blankIncludes = false) : string
|
||||
{
|
||||
$content = $this->page->html;
|
||||
|
||||
if (!config('app.allow_content_scripts')) {
|
||||
$content = $this->escapeScripts($content);
|
||||
}
|
||||
|
||||
if ($blankIncludes) {
|
||||
$content = $this->blankPageIncludes($content);
|
||||
} else {
|
||||
$content = $this->parsePageIncludes($content);
|
||||
}
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the headers on the page to get a navigation menu
|
||||
*/
|
||||
public function getNavigation(string $htmlContent): array
|
||||
{
|
||||
if (empty($htmlContent)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
libxml_use_internal_errors(true);
|
||||
$doc = new DOMDocument();
|
||||
$doc->loadHTML(mb_convert_encoding($htmlContent, 'HTML-ENTITIES', 'UTF-8'));
|
||||
$xPath = new DOMXPath($doc);
|
||||
$headers = $xPath->query("//h1|//h2|//h3|//h4|//h5|//h6");
|
||||
|
||||
return $headers ? $this->headerNodesToLevelList($headers) : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a DOMNodeList into an array of readable header attributes
|
||||
* with levels normalised to the lower header level.
|
||||
*/
|
||||
protected function headerNodesToLevelList(DOMNodeList $nodeList): array
|
||||
{
|
||||
$tree = collect($nodeList)->map(function ($header) {
|
||||
$text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
|
||||
$text = mb_substr($text, 0, 100);
|
||||
|
||||
return [
|
||||
'nodeName' => strtolower($header->nodeName),
|
||||
'level' => intval(str_replace('h', '', $header->nodeName)),
|
||||
'link' => '#' . $header->getAttribute('id'),
|
||||
'text' => $text,
|
||||
];
|
||||
})->filter(function ($header) {
|
||||
return mb_strlen($header['text']) > 0;
|
||||
});
|
||||
|
||||
// Shift headers if only smaller headers have been used
|
||||
$levelChange = ($tree->pluck('level')->min() - 1);
|
||||
$tree = $tree->map(function ($header) use ($levelChange) {
|
||||
$header['level'] -= ($levelChange);
|
||||
return $header;
|
||||
});
|
||||
|
||||
return $tree->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove any page include tags within the given HTML.
|
||||
*/
|
||||
protected function blankPageIncludes(string $html) : string
|
||||
{
|
||||
return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse any include tags "{{@<page_id>#section}}" to be part of the page.
|
||||
*/
|
||||
protected function parsePageIncludes(string $html) : string
|
||||
{
|
||||
$matches = [];
|
||||
preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
|
||||
|
||||
foreach ($matches[1] as $index => $includeId) {
|
||||
$fullMatch = $matches[0][$index];
|
||||
$splitInclude = explode('#', $includeId, 2);
|
||||
|
||||
// Get page id from reference
|
||||
$pageId = intval($splitInclude[0]);
|
||||
if (is_nan($pageId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Find page and skip this if page not found
|
||||
$matchedPage = Page::visible()->find($pageId);
|
||||
if ($matchedPage === null) {
|
||||
$html = str_replace($fullMatch, '', $html);
|
||||
continue;
|
||||
}
|
||||
|
||||
// If we only have page id, just insert all page html and continue.
|
||||
if (count($splitInclude) === 1) {
|
||||
$html = str_replace($fullMatch, $matchedPage->html, $html);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Create and load HTML into a document
|
||||
$innerContent = $this->fetchSectionOfPage($matchedPage, $splitInclude[1]);
|
||||
$html = str_replace($fullMatch, trim($innerContent), $html);
|
||||
}
|
||||
|
||||
return $html;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Fetch the content from a specific section of the given page.
|
||||
*/
|
||||
protected function fetchSectionOfPage(Page $page, string $sectionId): string
|
||||
{
|
||||
$topLevelTags = ['table', 'ul', 'ol'];
|
||||
$doc = new DOMDocument();
|
||||
libxml_use_internal_errors(true);
|
||||
$doc->loadHTML(mb_convert_encoding('<body>'.$page->html.'</body>', 'HTML-ENTITIES', 'UTF-8'));
|
||||
|
||||
// Search included content for the id given and blank out if not exists.
|
||||
$matchingElem = $doc->getElementById($sectionId);
|
||||
if ($matchingElem === null) {
|
||||
return '';
|
||||
}
|
||||
|
||||
// Otherwise replace the content with the found content
|
||||
// Checks if the top-level wrapper should be included by matching on tag types
|
||||
$innerContent = '';
|
||||
$isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
|
||||
if ($isTopLevel) {
|
||||
$innerContent .= $doc->saveHTML($matchingElem);
|
||||
} else {
|
||||
foreach ($matchingElem->childNodes as $childNode) {
|
||||
$innerContent .= $doc->saveHTML($childNode);
|
||||
}
|
||||
}
|
||||
libxml_clear_errors();
|
||||
|
||||
return $innerContent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape script tags within HTML content.
|
||||
*/
|
||||
protected function escapeScripts(string $html) : string
|
||||
{
|
||||
if (empty($html)) {
|
||||
return $html;
|
||||
}
|
||||
|
||||
libxml_use_internal_errors(true);
|
||||
$doc = new DOMDocument();
|
||||
$doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
|
||||
$xPath = new DOMXPath($doc);
|
||||
|
||||
// Remove standard script tags
|
||||
$scriptElems = $xPath->query('//script');
|
||||
foreach ($scriptElems as $scriptElem) {
|
||||
$scriptElem->parentNode->removeChild($scriptElem);
|
||||
}
|
||||
|
||||
// Remove data or JavaScript iFrames
|
||||
$badIframes = $xPath->query('//*[contains(@src, \'data:\')] | //*[contains(@src, \'javascript:\')] | //*[@srcdoc]');
|
||||
foreach ($badIframes as $badIframe) {
|
||||
$badIframe->parentNode->removeChild($badIframe);
|
||||
}
|
||||
|
||||
// Remove 'on*' attributes
|
||||
$onAttributes = $xPath->query('//@*[starts-with(name(), \'on\')]');
|
||||
foreach ($onAttributes as $attr) {
|
||||
/** @var \DOMAttr $attr*/
|
||||
$attrName = $attr->nodeName;
|
||||
$attr->parentNode->removeAttribute($attrName);
|
||||
}
|
||||
|
||||
$html = '';
|
||||
$topElems = $doc->documentElement->childNodes->item(0)->childNodes;
|
||||
foreach ($topElems as $child) {
|
||||
$html .= $doc->saveHTML($child);
|
||||
}
|
||||
|
||||
return $html;
|
||||
}
|
||||
}
|
74
app/Entities/Managers/PageEditActivity.php
Normal file
74
app/Entities/Managers/PageEditActivity.php
Normal file
@@ -0,0 +1,74 @@
|
||||
<?php namespace BookStack\Entities\Managers;
|
||||
|
||||
use BookStack\Entities\Page;
|
||||
use BookStack\Entities\PageRevision;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
class PageEditActivity
|
||||
{
|
||||
|
||||
protected $page;
|
||||
|
||||
/**
|
||||
* PageEditActivity constructor.
|
||||
*/
|
||||
public function __construct(Page $page)
|
||||
{
|
||||
$this->page = $page;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if there's active editing being performed on this page.
|
||||
* @return bool
|
||||
*/
|
||||
public function hasActiveEditing(): bool
|
||||
{
|
||||
return $this->activePageEditingQuery(60)->count() > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a notification message concerning the editing activity on the page.
|
||||
*/
|
||||
public function activeEditingMessage(): string
|
||||
{
|
||||
$pageDraftEdits = $this->activePageEditingQuery(60)->get();
|
||||
$count = $pageDraftEdits->count();
|
||||
|
||||
$userMessage = $count > 1 ? trans('entities.pages_draft_edit_active.start_a', ['count' => $count]): trans('entities.pages_draft_edit_active.start_b', ['userName' => $pageDraftEdits->first()->createdBy->name]);
|
||||
$timeMessage = trans('entities.pages_draft_edit_active.time_b', ['minCount'=> 60]);
|
||||
return trans('entities.pages_draft_edit_active.message', ['start' => $userMessage, 'time' => $timeMessage]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the message to show when the user will be editing one of their drafts.
|
||||
* @param PageRevision $draft
|
||||
* @return string
|
||||
*/
|
||||
public function getEditingActiveDraftMessage(PageRevision $draft): string
|
||||
{
|
||||
$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');
|
||||
}
|
||||
|
||||
/**
|
||||
* A query to check for active update drafts on a particular page
|
||||
* within the last given many minutes.
|
||||
*/
|
||||
protected function activePageEditingQuery(int $withinMinutes): Builder
|
||||
{
|
||||
$checkTime = Carbon::now()->subMinutes($withinMinutes);
|
||||
$query = PageRevision::query()
|
||||
->where('type', '=', 'update_draft')
|
||||
->where('page_id', '=', $this->page->id)
|
||||
->where('updated_at', '>', $this->page->updated_at)
|
||||
->where('created_by', '!=', user()->id)
|
||||
->where('updated_at', '>=', $checkTime)
|
||||
->with('createdBy');
|
||||
|
||||
return $query;
|
||||
}
|
||||
}
|
109
app/Entities/Managers/TrashCan.php
Normal file
109
app/Entities/Managers/TrashCan.php
Normal file
@@ -0,0 +1,109 @@
|
||||
<?php namespace BookStack\Entities\Managers;
|
||||
|
||||
use BookStack\Entities\Book;
|
||||
use BookStack\Entities\Bookshelf;
|
||||
use BookStack\Entities\Chapter;
|
||||
use BookStack\Entities\Entity;
|
||||
use BookStack\Entities\HasCoverImage;
|
||||
use BookStack\Entities\Page;
|
||||
use BookStack\Exceptions\NotifyException;
|
||||
use BookStack\Facades\Activity;
|
||||
use BookStack\Uploads\AttachmentService;
|
||||
use BookStack\Uploads\ImageService;
|
||||
use Exception;
|
||||
use Illuminate\Contracts\Container\BindingResolutionException;
|
||||
|
||||
class TrashCan
|
||||
{
|
||||
|
||||
/**
|
||||
* Remove a bookshelf from the system.
|
||||
* @throws Exception
|
||||
*/
|
||||
public function destroyShelf(Bookshelf $shelf)
|
||||
{
|
||||
$this->destroyCommonRelations($shelf);
|
||||
$shelf->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a book from the system.
|
||||
* @throws NotifyException
|
||||
* @throws BindingResolutionException
|
||||
*/
|
||||
public function destroyBook(Book $book)
|
||||
{
|
||||
foreach ($book->pages as $page) {
|
||||
$this->destroyPage($page);
|
||||
}
|
||||
|
||||
foreach ($book->chapters as $chapter) {
|
||||
$this->destroyChapter($chapter);
|
||||
}
|
||||
|
||||
$this->destroyCommonRelations($book);
|
||||
$book->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a page from the system.
|
||||
* @throws NotifyException
|
||||
*/
|
||||
public function destroyPage(Page $page)
|
||||
{
|
||||
// Check if set as custom homepage & remove setting if not used or throw error if active
|
||||
$customHome = setting('app-homepage', '0:');
|
||||
if (intval($page->id) === intval(explode(':', $customHome)[0])) {
|
||||
if (setting('app-homepage-type') === 'page') {
|
||||
throw new NotifyException(trans('errors.page_custom_home_deletion'), $page->getUrl());
|
||||
}
|
||||
setting()->remove('app-homepage');
|
||||
}
|
||||
|
||||
$this->destroyCommonRelations($page);
|
||||
|
||||
// Delete Attached Files
|
||||
$attachmentService = app(AttachmentService::class);
|
||||
foreach ($page->attachments as $attachment) {
|
||||
$attachmentService->deleteFile($attachment);
|
||||
}
|
||||
|
||||
$page->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a chapter from the system.
|
||||
* @throws Exception
|
||||
*/
|
||||
public function destroyChapter(Chapter $chapter)
|
||||
{
|
||||
if (count($chapter->pages) > 0) {
|
||||
foreach ($chapter->pages as $page) {
|
||||
$page->chapter_id = 0;
|
||||
$page->save();
|
||||
}
|
||||
}
|
||||
|
||||
$this->destroyCommonRelations($chapter);
|
||||
$chapter->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* Update entity relations to remove or update outstanding connections.
|
||||
*/
|
||||
protected function destroyCommonRelations(Entity $entity)
|
||||
{
|
||||
Activity::removeEntity($entity);
|
||||
$entity->views()->delete();
|
||||
$entity->permissions()->delete();
|
||||
$entity->tags()->delete();
|
||||
$entity->comments()->delete();
|
||||
$entity->jointPermissions()->delete();
|
||||
$entity->searchTerms()->delete();
|
||||
|
||||
if ($entity instanceof HasCoverImage && $entity->cover) {
|
||||
$imageService = app()->make(ImageService::class);
|
||||
$imageService->destroy($entity->cover);
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,7 +1,24 @@
|
||||
<?php namespace BookStack\Entities;
|
||||
|
||||
use BookStack\Uploads\Attachment;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Permissions;
|
||||
|
||||
/**
|
||||
* Class Page
|
||||
* @property int $chapter_id
|
||||
* @property string $html
|
||||
* @property string $markdown
|
||||
* @property string $text
|
||||
* @property bool $template
|
||||
* @property bool $draft
|
||||
* @property int $revision_count
|
||||
* @property Chapter $chapter
|
||||
* @property Collection $attachments
|
||||
*/
|
||||
class Page extends BookChild
|
||||
{
|
||||
protected $fillable = ['name', 'html', 'priority', 'markdown'];
|
||||
@@ -11,12 +28,12 @@ class Page extends BookChild
|
||||
public $textField = 'text';
|
||||
|
||||
/**
|
||||
* Get the morph class for this model.
|
||||
* @return string
|
||||
* Get the entities that are visible to the current user.
|
||||
*/
|
||||
public function getMorphClass()
|
||||
public function scopeVisible(Builder $query)
|
||||
{
|
||||
return 'BookStack\\Page';
|
||||
$query = Permissions::enforceDraftVisiblityOnQuery($query);
|
||||
return parent::scopeVisible($query);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -32,16 +49,15 @@ class Page extends BookChild
|
||||
|
||||
/**
|
||||
* Get the parent item
|
||||
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
|
||||
*/
|
||||
public function parent()
|
||||
public function parent(): Entity
|
||||
{
|
||||
return $this->chapter_id ? $this->chapter() : $this->book();
|
||||
return $this->chapter_id ? $this->chapter : $this->book;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the chapter that this page is in, If applicable.
|
||||
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
|
||||
* @return BelongsTo
|
||||
*/
|
||||
public function chapter()
|
||||
{
|
||||
@@ -63,12 +79,12 @@ class Page extends BookChild
|
||||
*/
|
||||
public function revisions()
|
||||
{
|
||||
return $this->hasMany(PageRevision::class)->where('type', '=', 'version')->orderBy('created_at', 'desc');
|
||||
return $this->hasMany(PageRevision::class)->where('type', '=', 'version')->orderBy('created_at', 'desc')->orderBy('id', 'desc');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the attachments assigned to this page.
|
||||
* @return \Illuminate\Database\Eloquent\Relations\HasMany
|
||||
* @return HasMany
|
||||
*/
|
||||
public function attachments()
|
||||
{
|
||||
@@ -86,27 +102,17 @@ class Page extends BookChild
|
||||
$midText = $this->draft ? '/draft/' : '/page/';
|
||||
$idComponent = $this->draft ? $this->id : urlencode($this->slug);
|
||||
|
||||
$url = '/books/' . urlencode($bookSlug) . $midText . $idComponent;
|
||||
if ($path !== false) {
|
||||
return url('/books/' . urlencode($bookSlug) . $midText . $idComponent . '/' . trim($path, '/'));
|
||||
$url .= '/' . trim($path, '/');
|
||||
}
|
||||
|
||||
return url('/books/' . urlencode($bookSlug) . $midText . $idComponent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a generalised, common raw query that can be 'unioned' across entities.
|
||||
* @param bool $withContent
|
||||
* @return string
|
||||
*/
|
||||
public function entityRawQuery($withContent = false)
|
||||
{
|
||||
$htmlQuery = $withContent ? 'html' : "'' as html";
|
||||
return "'BookStack\\\\Page' as entity_type, id, id as entity_id, slug, name, {$this->textField} as text, {$htmlQuery}, book_id, priority, chapter_id, draft, created_by, updated_by, updated_at, created_at";
|
||||
return url($url);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current revision for the page if existing
|
||||
* @return \BookStack\Entities\PageRevision|null
|
||||
* @return PageRevision|null
|
||||
*/
|
||||
public function getCurrentRevision()
|
||||
{
|
||||
|
@@ -2,7 +2,21 @@
|
||||
|
||||
use BookStack\Auth\User;
|
||||
use BookStack\Model;
|
||||
use Carbon\Carbon;
|
||||
|
||||
/**
|
||||
* Class PageRevision
|
||||
* @property int $page_id
|
||||
* @property string $slug
|
||||
* @property string $book_slug
|
||||
* @property int $created_by
|
||||
* @property Carbon $created_at
|
||||
* @property string $type
|
||||
* @property string $summary
|
||||
* @property string $markdown
|
||||
* @property string $html
|
||||
* @property int $revision_number
|
||||
*/
|
||||
class PageRevision extends Model
|
||||
{
|
||||
protected $fillable = ['name', 'html', 'text', 'markdown', 'summary'];
|
||||
@@ -41,13 +55,18 @@ class PageRevision extends Model
|
||||
|
||||
/**
|
||||
* Get the previous revision for the same page if existing
|
||||
* @return \BookStack\PageRevision|null
|
||||
* @return \BookStack\Entities\PageRevision|null
|
||||
*/
|
||||
public function getPrevious()
|
||||
{
|
||||
if ($id = static::where('page_id', '=', $this->page_id)->where('id', '<', $this->id)->max('id')) {
|
||||
return static::find($id);
|
||||
$id = static::newQuery()->where('page_id', '=', $this->page_id)
|
||||
->where('id', '<', $this->id)
|
||||
->max('id');
|
||||
|
||||
if ($id) {
|
||||
return static::query()->find($id);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
|
118
app/Entities/Repos/BaseRepo.php
Normal file
118
app/Entities/Repos/BaseRepo.php
Normal file
@@ -0,0 +1,118 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Entities\Repos;
|
||||
|
||||
use BookStack\Actions\TagRepo;
|
||||
use BookStack\Entities\Book;
|
||||
use BookStack\Entities\Entity;
|
||||
use BookStack\Entities\HasCoverImage;
|
||||
use BookStack\Exceptions\ImageUploadException;
|
||||
use BookStack\Uploads\ImageRepo;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class BaseRepo
|
||||
{
|
||||
|
||||
protected $tagRepo;
|
||||
protected $imageRepo;
|
||||
|
||||
|
||||
/**
|
||||
* BaseRepo constructor.
|
||||
* @param $tagRepo
|
||||
*/
|
||||
public function __construct(TagRepo $tagRepo, ImageRepo $imageRepo)
|
||||
{
|
||||
$this->tagRepo = $tagRepo;
|
||||
$this->imageRepo = $imageRepo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new entity in the system
|
||||
*/
|
||||
public function create(Entity $entity, array $input)
|
||||
{
|
||||
$entity->fill($input);
|
||||
$entity->forceFill([
|
||||
'created_by' => user()->id,
|
||||
'updated_by' => user()->id,
|
||||
]);
|
||||
$entity->refreshSlug();
|
||||
$entity->save();
|
||||
|
||||
if (isset($input['tags'])) {
|
||||
$this->tagRepo->saveTagsToEntity($entity, $input['tags']);
|
||||
}
|
||||
|
||||
$entity->rebuildPermissions();
|
||||
$entity->indexForSearch();
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the given entity.
|
||||
*/
|
||||
public function update(Entity $entity, array $input)
|
||||
{
|
||||
$entity->fill($input);
|
||||
$entity->updated_by = user()->id;
|
||||
|
||||
if ($entity->isDirty('name')) {
|
||||
$entity->refreshSlug();
|
||||
}
|
||||
|
||||
$entity->save();
|
||||
|
||||
if (isset($input['tags'])) {
|
||||
$this->tagRepo->saveTagsToEntity($entity, $input['tags']);
|
||||
}
|
||||
|
||||
$entity->rebuildPermissions();
|
||||
$entity->indexForSearch();
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the given items' cover image, or clear it.
|
||||
* @throws ImageUploadException
|
||||
* @throws \Exception
|
||||
*/
|
||||
public function updateCoverImage(HasCoverImage $entity, UploadedFile $coverImage = null, bool $removeImage = false)
|
||||
{
|
||||
if ($coverImage) {
|
||||
$this->imageRepo->destroyImage($entity->cover);
|
||||
$image = $this->imageRepo->saveNew($coverImage, 'cover_book', $entity->id, 512, 512, true);
|
||||
$entity->cover()->associate($image);
|
||||
}
|
||||
|
||||
if ($removeImage) {
|
||||
$this->imageRepo->destroyImage($entity->cover);
|
||||
$entity->image_id = 0;
|
||||
$entity->save();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the permissions of an entity.
|
||||
*/
|
||||
public function updatePermissions(Entity $entity, bool $restricted, Collection $permissions = null)
|
||||
{
|
||||
$entity->restricted = $restricted;
|
||||
$entity->permissions()->delete();
|
||||
|
||||
if (!is_null($permissions)) {
|
||||
$entityPermissionData = $permissions->flatMap(function ($restrictions, $roleId) {
|
||||
return collect($restrictions)->keys()->map(function ($action) use ($roleId) {
|
||||
return [
|
||||
'role_id' => $roleId,
|
||||
'action' => strtolower($action),
|
||||
] ;
|
||||
});
|
||||
});
|
||||
|
||||
$entity->permissions()->createMany($entityPermissionData);
|
||||
}
|
||||
|
||||
$entity->save();
|
||||
$entity->rebuildPermissions();
|
||||
}
|
||||
}
|
@@ -1,46 +1,134 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace BookStack\Entities\Repos;
|
||||
<?php namespace BookStack\Entities\Repos;
|
||||
|
||||
use BookStack\Actions\TagRepo;
|
||||
use BookStack\Entities\Book;
|
||||
use BookStack\Entities\Managers\TrashCan;
|
||||
use BookStack\Exceptions\ImageUploadException;
|
||||
use BookStack\Exceptions\NotFoundException;
|
||||
use BookStack\Exceptions\NotifyException;
|
||||
use BookStack\Uploads\ImageRepo;
|
||||
use Exception;
|
||||
use Illuminate\Contracts\Container\BindingResolutionException;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class BookRepo extends EntityRepo
|
||||
class BookRepo
|
||||
{
|
||||
|
||||
protected $baseRepo;
|
||||
protected $tagRepo;
|
||||
protected $imageRepo;
|
||||
|
||||
/**
|
||||
* Fetch a book by its slug.
|
||||
* @param string $slug
|
||||
* @return Book
|
||||
* @throws NotFoundException
|
||||
* BookRepo constructor.
|
||||
* @param $tagRepo
|
||||
*/
|
||||
public function __construct(BaseRepo $baseRepo, TagRepo $tagRepo, ImageRepo $imageRepo)
|
||||
{
|
||||
$this->baseRepo = $baseRepo;
|
||||
$this->tagRepo = $tagRepo;
|
||||
$this->imageRepo = $imageRepo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all books in a paginated format.
|
||||
*/
|
||||
public function getAllPaginated(int $count = 20, string $sort = 'name', string $order = 'asc'): LengthAwarePaginator
|
||||
{
|
||||
return Book::visible()->orderBy($sort, $order)->paginate($count);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the books that were most recently viewed by this user.
|
||||
*/
|
||||
public function getRecentlyViewed(int $count = 20): Collection
|
||||
{
|
||||
return Book::visible()->withLastView()
|
||||
->having('last_viewed_at', '>', 0)
|
||||
->orderBy('last_viewed_at', 'desc')
|
||||
->take($count)->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the most popular books in the system.
|
||||
*/
|
||||
public function getPopular(int $count = 20): Collection
|
||||
{
|
||||
return Book::visible()->withViewCount()
|
||||
->having('view_count', '>', 0)
|
||||
->orderBy('view_count', 'desc')
|
||||
->take($count)->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the most recently created books from the system.
|
||||
*/
|
||||
public function getRecentlyCreated(int $count = 20): Collection
|
||||
{
|
||||
return Book::visible()->orderBy('created_at', 'desc')
|
||||
->take($count)->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a book by its slug.
|
||||
*/
|
||||
public function getBySlug(string $slug): Book
|
||||
{
|
||||
/** @var Book $book */
|
||||
$book = $this->getEntityBySlug('book', $slug);
|
||||
$book = Book::visible()->where('slug', '=', $slug)->first();
|
||||
|
||||
if ($book === null) {
|
||||
throw new NotFoundException(trans('errors.book_not_found'));
|
||||
}
|
||||
|
||||
return $book;
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroy the provided book and all its child entities.
|
||||
* @param Book $book
|
||||
* @throws NotifyException
|
||||
* @throws \Throwable
|
||||
* Create a new book in the system
|
||||
*/
|
||||
public function destroyBook(Book $book)
|
||||
public function create(array $input): Book
|
||||
{
|
||||
foreach ($book->pages as $page) {
|
||||
$this->destroyPage($page);
|
||||
}
|
||||
|
||||
foreach ($book->chapters as $chapter) {
|
||||
$this->destroyChapter($chapter);
|
||||
}
|
||||
|
||||
$this->destroyEntityCommonRelations($book);
|
||||
$book->delete();
|
||||
$book = new Book();
|
||||
$this->baseRepo->create($book, $input);
|
||||
return $book;
|
||||
}
|
||||
|
||||
}
|
||||
/**
|
||||
* Update the given book.
|
||||
*/
|
||||
public function update(Book $book, array $input): Book
|
||||
{
|
||||
$this->baseRepo->update($book, $input);
|
||||
return $book;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the given book's cover image, or clear it.
|
||||
* @throws ImageUploadException
|
||||
* @throws Exception
|
||||
*/
|
||||
public function updateCoverImage(Book $book, UploadedFile $coverImage = null, bool $removeImage = false)
|
||||
{
|
||||
$this->baseRepo->updateCoverImage($book, $coverImage, $removeImage);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the permissions of a book.
|
||||
*/
|
||||
public function updatePermissions(Book $book, bool $restricted, Collection $permissions = null)
|
||||
{
|
||||
$this->baseRepo->updatePermissions($book, $restricted, $permissions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a book from the system.
|
||||
* @throws NotifyException
|
||||
* @throws BindingResolutionException
|
||||
*/
|
||||
public function destroy(Book $book)
|
||||
{
|
||||
$trashCan = new TrashCan();
|
||||
$trashCan->destroyBook($book);
|
||||
}
|
||||
}
|
||||
|
173
app/Entities/Repos/BookshelfRepo.php
Normal file
173
app/Entities/Repos/BookshelfRepo.php
Normal file
@@ -0,0 +1,173 @@
|
||||
<?php namespace BookStack\Entities\Repos;
|
||||
|
||||
use BookStack\Entities\Book;
|
||||
use BookStack\Entities\Bookshelf;
|
||||
use BookStack\Entities\Managers\TrashCan;
|
||||
use BookStack\Exceptions\ImageUploadException;
|
||||
use BookStack\Exceptions\NotFoundException;
|
||||
use Exception;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class BookshelfRepo
|
||||
{
|
||||
protected $baseRepo;
|
||||
|
||||
/**
|
||||
* BookshelfRepo constructor.
|
||||
* @param $baseRepo
|
||||
*/
|
||||
public function __construct(BaseRepo $baseRepo)
|
||||
{
|
||||
$this->baseRepo = $baseRepo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all bookshelves in a paginated format.
|
||||
*/
|
||||
public function getAllPaginated(int $count = 20, string $sort = 'name', string $order = 'asc'): LengthAwarePaginator
|
||||
{
|
||||
return Bookshelf::visible()->with('visibleBooks')
|
||||
->orderBy($sort, $order)->paginate($count);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the bookshelves that were most recently viewed by this user.
|
||||
*/
|
||||
public function getRecentlyViewed(int $count = 20): Collection
|
||||
{
|
||||
return Bookshelf::visible()->withLastView()
|
||||
->having('last_viewed_at', '>', 0)
|
||||
->orderBy('last_viewed_at', 'desc')
|
||||
->take($count)->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the most popular bookshelves in the system.
|
||||
*/
|
||||
public function getPopular(int $count = 20): Collection
|
||||
{
|
||||
return Bookshelf::visible()->withViewCount()
|
||||
->having('view_count', '>', 0)
|
||||
->orderBy('view_count', 'desc')
|
||||
->take($count)->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the most recently created bookshelves from the system.
|
||||
*/
|
||||
public function getRecentlyCreated(int $count = 20): Collection
|
||||
{
|
||||
return Bookshelf::visible()->orderBy('created_at', 'desc')
|
||||
->take($count)->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a shelf by its slug.
|
||||
*/
|
||||
public function getBySlug(string $slug): Bookshelf
|
||||
{
|
||||
$shelf = Bookshelf::visible()->where('slug', '=', $slug)->first();
|
||||
|
||||
if ($shelf === null) {
|
||||
throw new NotFoundException(trans('errors.bookshelf_not_found'));
|
||||
}
|
||||
|
||||
return $shelf;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new shelf in the system.
|
||||
*/
|
||||
public function create(array $input, array $bookIds): Bookshelf
|
||||
{
|
||||
$shelf = new Bookshelf();
|
||||
$this->baseRepo->create($shelf, $input);
|
||||
$this->updateBooks($shelf, $bookIds);
|
||||
return $shelf;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new shelf in the system.
|
||||
*/
|
||||
public function update(Bookshelf $shelf, array $input, array $bookIds): Bookshelf
|
||||
{
|
||||
$this->baseRepo->update($shelf, $input);
|
||||
$this->updateBooks($shelf, $bookIds);
|
||||
return $shelf;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update which books are assigned to this shelf by
|
||||
* syncing the given book ids.
|
||||
* Function ensures the books are visible to the current user and existing.
|
||||
*/
|
||||
protected function updateBooks(Bookshelf $shelf, array $bookIds)
|
||||
{
|
||||
$numericIDs = collect($bookIds)->map(function ($id) {
|
||||
return intval($id);
|
||||
});
|
||||
|
||||
$syncData = Book::visible()
|
||||
->whereIn('id', $bookIds)
|
||||
->get(['id'])->pluck('id')->mapWithKeys(function ($bookId) use ($numericIDs) {
|
||||
return [$bookId => ['order' => $numericIDs->search($bookId)]];
|
||||
});
|
||||
|
||||
$shelf->books()->sync($syncData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the given shelf cover image, or clear it.
|
||||
* @throws ImageUploadException
|
||||
* @throws Exception
|
||||
*/
|
||||
public function updateCoverImage(Bookshelf $shelf, UploadedFile $coverImage = null, bool $removeImage = false)
|
||||
{
|
||||
$this->baseRepo->updateCoverImage($shelf, $coverImage, $removeImage);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the permissions of a bookshelf.
|
||||
*/
|
||||
public function updatePermissions(Bookshelf $shelf, bool $restricted, Collection $permissions = null)
|
||||
{
|
||||
$this->baseRepo->updatePermissions($shelf, $restricted, $permissions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy down the permissions of the given shelf to all child books.
|
||||
*/
|
||||
public function copyDownPermissions(Bookshelf $shelf): int
|
||||
{
|
||||
$shelfPermissions = $shelf->permissions()->get(['role_id', 'action'])->toArray();
|
||||
$shelfBooks = $shelf->books()->get();
|
||||
$updatedBookCount = 0;
|
||||
|
||||
/** @var Book $book */
|
||||
foreach ($shelfBooks as $book) {
|
||||
if (!userCan('restrictions-manage', $book)) {
|
||||
continue;
|
||||
}
|
||||
$book->permissions()->delete();
|
||||
$book->restricted = $shelf->restricted;
|
||||
$book->permissions()->createMany($shelfPermissions);
|
||||
$book->save();
|
||||
$book->rebuildPermissions();
|
||||
$updatedBookCount++;
|
||||
}
|
||||
|
||||
return $updatedBookCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a bookshelf from the system.
|
||||
* @throws Exception
|
||||
*/
|
||||
public function destroy(Bookshelf $shelf)
|
||||
{
|
||||
$trashCan = new TrashCan();
|
||||
$trashCan->destroyShelf($shelf);
|
||||
}
|
||||
}
|
108
app/Entities/Repos/ChapterRepo.php
Normal file
108
app/Entities/Repos/ChapterRepo.php
Normal file
@@ -0,0 +1,108 @@
|
||||
<?php namespace BookStack\Entities\Repos;
|
||||
|
||||
use BookStack\Entities\Book;
|
||||
use BookStack\Entities\Chapter;
|
||||
use BookStack\Entities\Managers\BookContents;
|
||||
use BookStack\Entities\Managers\TrashCan;
|
||||
use BookStack\Exceptions\MoveOperationException;
|
||||
use BookStack\Exceptions\NotFoundException;
|
||||
use BookStack\Exceptions\NotifyException;
|
||||
use Exception;
|
||||
use Illuminate\Contracts\Container\BindingResolutionException;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class ChapterRepo
|
||||
{
|
||||
|
||||
protected $baseRepo;
|
||||
|
||||
/**
|
||||
* ChapterRepo constructor.
|
||||
* @param $baseRepo
|
||||
*/
|
||||
public function __construct(BaseRepo $baseRepo)
|
||||
{
|
||||
$this->baseRepo = $baseRepo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a chapter via the slug.
|
||||
* @throws NotFoundException
|
||||
*/
|
||||
public function getBySlug(string $bookSlug, string $chapterSlug): Chapter
|
||||
{
|
||||
$chapter = Chapter::visible()->whereSlugs($bookSlug, $chapterSlug)->first();
|
||||
|
||||
if ($chapter === null) {
|
||||
throw new NotFoundException(trans('errors.chapter_not_found'));
|
||||
}
|
||||
|
||||
return $chapter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new chapter in the system.
|
||||
*/
|
||||
public function create(array $input, Book $parentBook): Chapter
|
||||
{
|
||||
$chapter = new Chapter();
|
||||
$chapter->book_id = $parentBook->id;
|
||||
$chapter->priority = (new BookContents($parentBook))->getLastPriority() + 1;
|
||||
$this->baseRepo->create($chapter, $input);
|
||||
return $chapter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the given chapter.
|
||||
*/
|
||||
public function update(Chapter $chapter, array $input): Chapter
|
||||
{
|
||||
$this->baseRepo->update($chapter, $input);
|
||||
return $chapter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the permissions of a chapter.
|
||||
*/
|
||||
public function updatePermissions(Chapter $chapter, bool $restricted, Collection $permissions = null)
|
||||
{
|
||||
$this->baseRepo->updatePermissions($chapter, $restricted, $permissions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a chapter from the system.
|
||||
* @throws Exception
|
||||
*/
|
||||
public function destroy(Chapter $chapter)
|
||||
{
|
||||
$trashCan = new TrashCan();
|
||||
$trashCan->destroyChapter($chapter);
|
||||
}
|
||||
|
||||
/**
|
||||
* Move the given chapter into a new parent book.
|
||||
* The $parentIdentifier must be a string of the following format:
|
||||
* 'book:<id>' (book:5)
|
||||
* @throws MoveOperationException
|
||||
*/
|
||||
public function move(Chapter $chapter, string $parentIdentifier): Book
|
||||
{
|
||||
$stringExploded = explode(':', $parentIdentifier);
|
||||
$entityType = $stringExploded[0];
|
||||
$entityId = intval($stringExploded[1]);
|
||||
|
||||
if ($entityType !== 'book') {
|
||||
throw new MoveOperationException('Chapters can only be moved into books');
|
||||
}
|
||||
|
||||
$parent = Book::visible()->where('id', '=', $entityId)->first();
|
||||
if ($parent === null) {
|
||||
throw new MoveOperationException('Book to move chapter into not found');
|
||||
}
|
||||
|
||||
$chapter->changeBook($parent->id);
|
||||
$chapter->rebuildPermissions();
|
||||
return $parent;
|
||||
}
|
||||
}
|
@@ -1,843 +0,0 @@
|
||||
<?php namespace BookStack\Entities\Repos;
|
||||
|
||||
use Activity;
|
||||
use BookStack\Actions\TagRepo;
|
||||
use BookStack\Actions\ViewService;
|
||||
use BookStack\Auth\Permissions\PermissionService;
|
||||
use BookStack\Auth\User;
|
||||
use BookStack\Entities\Book;
|
||||
use BookStack\Entities\BookChild;
|
||||
use BookStack\Entities\Bookshelf;
|
||||
use BookStack\Entities\Chapter;
|
||||
use BookStack\Entities\Entity;
|
||||
use BookStack\Entities\EntityProvider;
|
||||
use BookStack\Entities\Page;
|
||||
use BookStack\Entities\SearchService;
|
||||
use BookStack\Exceptions\NotFoundException;
|
||||
use BookStack\Exceptions\NotifyException;
|
||||
use BookStack\Uploads\AttachmentService;
|
||||
use DOMDocument;
|
||||
use DOMXPath;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Query\Builder as QueryBuilder;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Collection;
|
||||
use Throwable;
|
||||
|
||||
class EntityRepo
|
||||
{
|
||||
|
||||
/**
|
||||
* @var EntityProvider
|
||||
*/
|
||||
protected $entityProvider;
|
||||
|
||||
/**
|
||||
* @var PermissionService
|
||||
*/
|
||||
protected $permissionService;
|
||||
|
||||
/**
|
||||
* @var ViewService
|
||||
*/
|
||||
protected $viewService;
|
||||
|
||||
/**
|
||||
* @var TagRepo
|
||||
*/
|
||||
protected $tagRepo;
|
||||
|
||||
/**
|
||||
* @var SearchService
|
||||
*/
|
||||
protected $searchService;
|
||||
|
||||
/**
|
||||
* EntityRepo constructor.
|
||||
* @param EntityProvider $entityProvider
|
||||
* @param ViewService $viewService
|
||||
* @param PermissionService $permissionService
|
||||
* @param TagRepo $tagRepo
|
||||
* @param SearchService $searchService
|
||||
*/
|
||||
public function __construct(
|
||||
EntityProvider $entityProvider,
|
||||
ViewService $viewService,
|
||||
PermissionService $permissionService,
|
||||
TagRepo $tagRepo,
|
||||
SearchService $searchService
|
||||
) {
|
||||
$this->entityProvider = $entityProvider;
|
||||
$this->viewService = $viewService;
|
||||
$this->permissionService = $permissionService;
|
||||
$this->tagRepo = $tagRepo;
|
||||
$this->searchService = $searchService;
|
||||
}
|
||||
|
||||
/**
|
||||
* Base query for searching entities via permission system
|
||||
* @param string $type
|
||||
* @param bool $allowDrafts
|
||||
* @param string $permission
|
||||
* @return QueryBuilder
|
||||
*/
|
||||
protected function entityQuery($type, $allowDrafts = false, $permission = 'view')
|
||||
{
|
||||
$q = $this->permissionService->enforceEntityRestrictions($type, $this->entityProvider->get($type), $permission);
|
||||
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
|
||||
* @param bool $ignorePermissions
|
||||
* @return Entity
|
||||
*/
|
||||
public function getById($type, $id, $allowDrafts = false, $ignorePermissions = false)
|
||||
{
|
||||
$query = $this->entityQuery($type, $allowDrafts);
|
||||
|
||||
if ($ignorePermissions) {
|
||||
$query = $this->entityProvider->get($type)->newQuery();
|
||||
}
|
||||
|
||||
return $query->find($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $type
|
||||
* @param []int $ids
|
||||
* @param bool $allowDrafts
|
||||
* @param bool $ignorePermissions
|
||||
* @return Builder[]|\Illuminate\Database\Eloquent\Collection|Collection
|
||||
*/
|
||||
public function getManyById($type, $ids, $allowDrafts = false, $ignorePermissions = false)
|
||||
{
|
||||
$query = $this->entityQuery($type, $allowDrafts);
|
||||
|
||||
if ($ignorePermissions) {
|
||||
$query = $this->entityProvider->get($type)->newQuery();
|
||||
}
|
||||
|
||||
return $query->whereIn('id', $ids)->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an entity by its url slug.
|
||||
* @param string $type
|
||||
* @param string $slug
|
||||
* @param string|null $bookSlug
|
||||
* @return Entity
|
||||
* @throws NotFoundException
|
||||
*/
|
||||
public function getEntityBySlug(string $type, string $slug, string $bookSlug = null): Entity
|
||||
{
|
||||
$type = strtolower($type);
|
||||
$query = $this->entityQuery($type)->where('slug', '=', $slug);
|
||||
|
||||
if ($type === 'chapter' || $type === 'page') {
|
||||
$query = $query->where('book_id', '=', function (QueryBuilder $query) use ($bookSlug) {
|
||||
$query->select('id')
|
||||
->from($this->entityProvider->book->getTable())
|
||||
->where('slug', '=', $bookSlug)->limit(1);
|
||||
});
|
||||
}
|
||||
|
||||
$entity = $query->first();
|
||||
|
||||
if ($entity === null) {
|
||||
throw new NotFoundException(trans('errors.' . $type . '_not_found'));
|
||||
}
|
||||
|
||||
return $entity;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get all entities of a type with the given permission, limited by count unless count is false.
|
||||
* @param string $type
|
||||
* @param integer|bool $count
|
||||
* @param string $permission
|
||||
* @return Collection
|
||||
*/
|
||||
public function getAll($type, $count = 20, $permission = 'view')
|
||||
{
|
||||
$q = $this->entityQuery($type, false, $permission)->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
|
||||
* @param string $sort
|
||||
* @param string $order
|
||||
* @param null|callable $queryAddition
|
||||
* @return LengthAwarePaginator
|
||||
*/
|
||||
public function getAllPaginated($type, int $count = 10, string $sort = 'name', string $order = 'asc', $queryAddition = null)
|
||||
{
|
||||
$query = $this->entityQuery($type);
|
||||
$query = $this->addSortToQuery($query, $sort, $order);
|
||||
if ($queryAddition) {
|
||||
$queryAddition($query);
|
||||
}
|
||||
return $query->paginate($count);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add sorting operations to an entity query.
|
||||
* @param Builder $query
|
||||
* @param string $sort
|
||||
* @param string $order
|
||||
* @return Builder
|
||||
*/
|
||||
protected function addSortToQuery(Builder $query, string $sort = 'name', string $order = 'asc')
|
||||
{
|
||||
$order = ($order === 'asc') ? 'asc' : 'desc';
|
||||
$propertySorts = ['name', 'created_at', 'updated_at'];
|
||||
|
||||
if (in_array($sort, $propertySorts)) {
|
||||
return $query->orderBy($sort, $order);
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the most recently created entities of the given type.
|
||||
* @param string $type
|
||||
* @param int $count
|
||||
* @param int $page
|
||||
* @param bool|callable $additionalQuery
|
||||
* @return Collection
|
||||
*/
|
||||
public function getRecentlyCreated($type, $count = 20, $page = 0, $additionalQuery = false)
|
||||
{
|
||||
$query = $this->permissionService->enforceEntityRestrictions($type, $this->entityProvider->get($type))
|
||||
->orderBy('created_at', 'desc');
|
||||
if (strtolower($type) === 'page') {
|
||||
$query = $query->where('draft', '=', false);
|
||||
}
|
||||
if ($additionalQuery !== false && is_callable($additionalQuery)) {
|
||||
$additionalQuery($query);
|
||||
}
|
||||
return $query->skip($page * $count)->take($count)->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the most recently updated entities of the given type.
|
||||
* @param string $type
|
||||
* @param int $count
|
||||
* @param int $page
|
||||
* @param bool|callable $additionalQuery
|
||||
* @return Collection
|
||||
*/
|
||||
public function getRecentlyUpdated($type, $count = 20, $page = 0, $additionalQuery = false)
|
||||
{
|
||||
$query = $this->permissionService->enforceEntityRestrictions($type, $this->entityProvider->get($type))
|
||||
->orderBy('updated_at', 'desc');
|
||||
if (strtolower($type) === 'page') {
|
||||
$query = $query->where('draft', '=', false);
|
||||
}
|
||||
if ($additionalQuery !== false && is_callable($additionalQuery)) {
|
||||
$additionalQuery($query);
|
||||
}
|
||||
return $query->skip($page * $count)->take($count)->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the most recently viewed entities.
|
||||
* @param string|bool $type
|
||||
* @param int $count
|
||||
* @param int $page
|
||||
* @return mixed
|
||||
*/
|
||||
public function getRecentlyViewed($type, $count = 10, $page = 0)
|
||||
{
|
||||
$filter = is_bool($type) ? false : $this->entityProvider->get($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 $type
|
||||
* @param int $count
|
||||
* @param int $page
|
||||
* @return mixed
|
||||
*/
|
||||
public function getPopular(string $type, int $count = 10, int $page = 0)
|
||||
{
|
||||
return $this->viewService->getPopular($count, $page, $type);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get draft pages owned by the current user.
|
||||
* @param int $count
|
||||
* @param int $page
|
||||
* @return Collection
|
||||
*/
|
||||
public function getUserDraftPages($count = 20, $page = 0)
|
||||
{
|
||||
return $this->entityProvider->page->where('draft', '=', true)
|
||||
->where('created_by', '=', user()->id)
|
||||
->orderBy('updated_at', 'desc')
|
||||
->skip($count * $page)->take($count)->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of entities the given user has created.
|
||||
* @param string $type
|
||||
* @param User $user
|
||||
* @return int
|
||||
*/
|
||||
public function getUserTotalCreated(string $type, User $user)
|
||||
{
|
||||
return $this->entityProvider->get($type)
|
||||
->where('created_by', '=', $user->id)->count();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the child items for a chapter sorted by priority but
|
||||
* with draft items floated to the top.
|
||||
* @param Bookshelf $bookshelf
|
||||
* @return \Illuminate\Database\Eloquent\Collection|static[]
|
||||
*/
|
||||
public function getBookshelfChildren(Bookshelf $bookshelf)
|
||||
{
|
||||
return $this->permissionService->enforceEntityRestrictions('book', $bookshelf->books())->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the direct children of a book.
|
||||
* @param Book $book
|
||||
* @return \Illuminate\Database\Eloquent\Collection
|
||||
*/
|
||||
public function getBookDirectChildren(Book $book)
|
||||
{
|
||||
$pages = $this->permissionService->enforceEntityRestrictions('page', $book->directPages())->get();
|
||||
$chapters = $this->permissionService->enforceEntityRestrictions('chapters', $book->chapters())->get();
|
||||
return collect()->concat($pages)->concat($chapters)->sortBy('priority')->sortByDesc('draft');
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* @param bool $renderPages
|
||||
* @return mixed
|
||||
*/
|
||||
public function getBookChildren(Book $book, $filterDrafts = false, $renderPages = false)
|
||||
{
|
||||
$q = $this->permissionService->bookChildrenQuery($book->id, $filterDrafts, $renderPages)->get();
|
||||
$entities = [];
|
||||
$parents = [];
|
||||
$tree = [];
|
||||
|
||||
foreach ($q as $index => $rawEntity) {
|
||||
if ($rawEntity->entity_type === $this->entityProvider->page->getMorphClass()) {
|
||||
$entities[$index] = $this->entityProvider->page->newFromBuilder($rawEntity);
|
||||
if ($renderPages) {
|
||||
$entities[$index]->html = $rawEntity->html;
|
||||
$entities[$index]->html = $this->renderPage($entities[$index]);
|
||||
};
|
||||
} else if ($rawEntity->entity_type === $this->entityProvider->chapter->getMorphClass()) {
|
||||
$entities[$index] = $this->entityProvider->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 || $entities[$index]->chapter_id === '0') {
|
||||
$tree[] = $entities[$index];
|
||||
}
|
||||
$entities[$index]->book = $book;
|
||||
}
|
||||
|
||||
foreach ($entities as $entity) {
|
||||
if ($entity->chapter_id === 0 || $entity->chapter_id === '0') {
|
||||
continue;
|
||||
}
|
||||
$parentKey = $this->entityProvider->chapter->getMorphClass() . ':' . $entity->chapter_id;
|
||||
if (!isset($parents[$parentKey])) {
|
||||
$tree[] = $entity;
|
||||
continue;
|
||||
}
|
||||
$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
|
||||
* @return \Illuminate\Database\Eloquent\Collection|static[]
|
||||
*/
|
||||
public function getChapterChildren(Chapter $chapter)
|
||||
{
|
||||
return $this->permissionService->enforceEntityRestrictions('page', $chapter->pages())
|
||||
->orderBy('draft', 'DESC')->orderBy('priority', 'ASC')->get();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Updates entity restrictions from a request
|
||||
* @param Request $request
|
||||
* @param Entity $entity
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function updateEntityPermissionsFromRequest(Request $request, Entity $entity)
|
||||
{
|
||||
$entity->restricted = $request->get('restricted', '') === 'true';
|
||||
$entity->permissions()->delete();
|
||||
|
||||
if ($request->filled('restrictions')) {
|
||||
$entityPermissionData = collect($request->get('restrictions'))->flatMap(function($restrictions, $roleId) {
|
||||
return collect($restrictions)->keys()->map(function($action) use ($roleId) {
|
||||
return [
|
||||
'role_id' => $roleId,
|
||||
'action' => strtolower($action),
|
||||
] ;
|
||||
});
|
||||
});
|
||||
|
||||
$entity->permissions()->createMany($entityPermissionData);
|
||||
}
|
||||
|
||||
$entity->save();
|
||||
$entity->rebuildPermissions();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Create a new entity from request input.
|
||||
* Used for books and chapters.
|
||||
* @param string $type
|
||||
* @param array $input
|
||||
* @param Book|null $book
|
||||
* @return Entity
|
||||
*/
|
||||
public function createFromInput(string $type, array $input = [], Book $book = null)
|
||||
{
|
||||
$entityModel = $this->entityProvider->get($type)->newInstance($input);
|
||||
$entityModel->created_by = user()->id;
|
||||
$entityModel->updated_by = user()->id;
|
||||
|
||||
if ($book) {
|
||||
$entityModel->book_id = $book->id;
|
||||
}
|
||||
|
||||
$entityModel->refreshSlug();
|
||||
$entityModel->save();
|
||||
|
||||
if (isset($input['tags'])) {
|
||||
$this->tagRepo->saveTagsToEntity($entityModel, $input['tags']);
|
||||
}
|
||||
|
||||
$entityModel->rebuildPermissions();
|
||||
$this->searchService->indexEntity($entityModel);
|
||||
return $entityModel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update entity details from request input.
|
||||
* Used for shelves, books and chapters.
|
||||
*/
|
||||
public function updateFromInput(Entity $entityModel, array $input): Entity
|
||||
{
|
||||
$entityModel->fill($input);
|
||||
$entityModel->updated_by = user()->id;
|
||||
|
||||
if ($entityModel->isDirty('name')) {
|
||||
$entityModel->refreshSlug();
|
||||
}
|
||||
|
||||
$entityModel->save();
|
||||
|
||||
if (isset($input['tags'])) {
|
||||
$this->tagRepo->saveTagsToEntity($entityModel, $input['tags']);
|
||||
}
|
||||
|
||||
$entityModel->rebuildPermissions();
|
||||
$this->searchService->indexEntity($entityModel);
|
||||
return $entityModel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync the books assigned to a shelf from a comma-separated list
|
||||
* of book IDs.
|
||||
* @param Bookshelf $shelf
|
||||
* @param string $books
|
||||
*/
|
||||
public function updateShelfBooks(Bookshelf $shelf, string $books)
|
||||
{
|
||||
$ids = explode(',', $books);
|
||||
|
||||
// Check books exist and match ordering
|
||||
$bookIds = $this->entityQuery('book')->whereIn('id', $ids)->get(['id'])->pluck('id');
|
||||
$syncData = [];
|
||||
foreach ($ids as $index => $id) {
|
||||
if ($bookIds->contains($id)) {
|
||||
$syncData[$id] = ['order' => $index];
|
||||
}
|
||||
}
|
||||
|
||||
$shelf->books()->sync($syncData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Change the book that an entity belongs to.
|
||||
*/
|
||||
public function changeBook(BookChild $bookChild, int $newBookId): Entity
|
||||
{
|
||||
$bookChild->book_id = $newBookId;
|
||||
$bookChild->refreshSlug();
|
||||
$bookChild->save();
|
||||
|
||||
// Update related activity
|
||||
$bookChild->activity()->update(['book_id' => $newBookId]);
|
||||
|
||||
// Update all child pages if a chapter
|
||||
if ($bookChild->isA('chapter')) {
|
||||
foreach ($bookChild->pages as $page) {
|
||||
$this->changeBook($page, $newBookId);
|
||||
}
|
||||
}
|
||||
|
||||
return $bookChild;
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the page for viewing
|
||||
* @param Page $page
|
||||
* @param bool $blankIncludes
|
||||
* @return string
|
||||
*/
|
||||
public function renderPage(Page $page, bool $blankIncludes = false) : string
|
||||
{
|
||||
$content = $page->html;
|
||||
|
||||
if (!config('app.allow_content_scripts')) {
|
||||
$content = $this->escapeScripts($content);
|
||||
}
|
||||
|
||||
if ($blankIncludes) {
|
||||
$content = $this->blankPageIncludes($content);
|
||||
} else {
|
||||
$content = $this->parsePageIncludes($content);
|
||||
}
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove any page include tags within the given HTML.
|
||||
* @param string $html
|
||||
* @return string
|
||||
*/
|
||||
protected function blankPageIncludes(string $html) : string
|
||||
{
|
||||
return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse any include tags "{{@<page_id>#section}}" to be part of the page.
|
||||
* @param string $html
|
||||
* @return mixed|string
|
||||
*/
|
||||
protected function parsePageIncludes(string $html) : string
|
||||
{
|
||||
$matches = [];
|
||||
preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
|
||||
|
||||
$topLevelTags = ['table', 'ul', 'ol'];
|
||||
foreach ($matches[1] as $index => $includeId) {
|
||||
$splitInclude = explode('#', $includeId, 2);
|
||||
$pageId = intval($splitInclude[0]);
|
||||
if (is_nan($pageId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$matchedPage = $this->getById('page', $pageId);
|
||||
if ($matchedPage === null) {
|
||||
$html = str_replace($matches[0][$index], '', $html);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (count($splitInclude) === 1) {
|
||||
$html = str_replace($matches[0][$index], $matchedPage->html, $html);
|
||||
continue;
|
||||
}
|
||||
|
||||
$doc = new DOMDocument();
|
||||
libxml_use_internal_errors(true);
|
||||
$doc->loadHTML(mb_convert_encoding('<body>'.$matchedPage->html.'</body>', 'HTML-ENTITIES', 'UTF-8'));
|
||||
$matchingElem = $doc->getElementById($splitInclude[1]);
|
||||
if ($matchingElem === null) {
|
||||
$html = str_replace($matches[0][$index], '', $html);
|
||||
continue;
|
||||
}
|
||||
$innerContent = '';
|
||||
$isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
|
||||
if ($isTopLevel) {
|
||||
$innerContent .= $doc->saveHTML($matchingElem);
|
||||
} else {
|
||||
foreach ($matchingElem->childNodes as $childNode) {
|
||||
$innerContent .= $doc->saveHTML($childNode);
|
||||
}
|
||||
}
|
||||
libxml_clear_errors();
|
||||
$html = str_replace($matches[0][$index], trim($innerContent), $html);
|
||||
}
|
||||
|
||||
return $html;
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape script tags within HTML content.
|
||||
* @param string $html
|
||||
* @return string
|
||||
*/
|
||||
protected function escapeScripts(string $html) : string
|
||||
{
|
||||
if ($html == '') {
|
||||
return $html;
|
||||
}
|
||||
|
||||
libxml_use_internal_errors(true);
|
||||
$doc = new DOMDocument();
|
||||
$doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
|
||||
$xPath = new DOMXPath($doc);
|
||||
|
||||
// Remove standard script tags
|
||||
$scriptElems = $xPath->query('//script');
|
||||
foreach ($scriptElems as $scriptElem) {
|
||||
$scriptElem->parentNode->removeChild($scriptElem);
|
||||
}
|
||||
|
||||
// Remove data or JavaScript iFrames
|
||||
$badIframes = $xPath->query('//*[contains(@src, \'data:\')] | //*[contains(@src, \'javascript:\')] | //*[@srcdoc]');
|
||||
foreach ($badIframes as $badIframe) {
|
||||
$badIframe->parentNode->removeChild($badIframe);
|
||||
}
|
||||
|
||||
// Remove 'on*' attributes
|
||||
$onAttributes = $xPath->query('//@*[starts-with(name(), \'on\')]');
|
||||
foreach ($onAttributes as $attr) {
|
||||
/** @var \DOMAttr $attr*/
|
||||
$attrName = $attr->nodeName;
|
||||
$attr->parentNode->removeAttribute($attrName);
|
||||
}
|
||||
|
||||
$html = '';
|
||||
$topElems = $doc->documentElement->childNodes->item(0)->childNodes;
|
||||
foreach ($topElems as $child) {
|
||||
$html .= $doc->saveHTML($child);
|
||||
}
|
||||
|
||||
return $html;
|
||||
}
|
||||
|
||||
/**
|
||||
* Search for image usage within page content.
|
||||
* @param $imageString
|
||||
* @return mixed
|
||||
*/
|
||||
public function searchForImage($imageString)
|
||||
{
|
||||
$pages = $this->entityQuery('page')->where('html', 'like', '%' . $imageString . '%')->get(['id', 'name', 'slug', 'book_id']);
|
||||
foreach ($pages as $page) {
|
||||
$page->url = $page->getUrl();
|
||||
$page->html = '';
|
||||
$page->text = '';
|
||||
}
|
||||
return count($pages) > 0 ? $pages : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroy a bookshelf instance
|
||||
* @param Bookshelf $shelf
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function destroyBookshelf(Bookshelf $shelf)
|
||||
{
|
||||
$this->destroyEntityCommonRelations($shelf);
|
||||
$shelf->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroy a chapter and its relations.
|
||||
* @param Chapter $chapter
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function destroyChapter(Chapter $chapter)
|
||||
{
|
||||
if (count($chapter->pages) > 0) {
|
||||
foreach ($chapter->pages as $page) {
|
||||
$page->chapter_id = 0;
|
||||
$page->save();
|
||||
}
|
||||
}
|
||||
$this->destroyEntityCommonRelations($chapter);
|
||||
$chapter->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroy a given page along with its dependencies.
|
||||
* @param Page $page
|
||||
* @throws NotifyException
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function destroyPage(Page $page)
|
||||
{
|
||||
// Check if set as custom homepage & remove setting if not used or throw error if active
|
||||
$customHome = setting('app-homepage', '0:');
|
||||
if (intval($page->id) === intval(explode(':', $customHome)[0])) {
|
||||
if (setting('app-homepage-type') === 'page') {
|
||||
throw new NotifyException(trans('errors.page_custom_home_deletion'), $page->getUrl());
|
||||
}
|
||||
setting()->remove('app-homepage');
|
||||
}
|
||||
|
||||
$this->destroyEntityCommonRelations($page);
|
||||
|
||||
// Delete Attached Files
|
||||
$attachmentService = app(AttachmentService::class);
|
||||
foreach ($page->attachments as $attachment) {
|
||||
$attachmentService->deleteFile($attachment);
|
||||
}
|
||||
|
||||
$page->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroy or handle the common relations connected to an entity.
|
||||
* @param Entity $entity
|
||||
* @throws Throwable
|
||||
*/
|
||||
protected function destroyEntityCommonRelations(Entity $entity)
|
||||
{
|
||||
Activity::removeEntity($entity);
|
||||
$entity->views()->delete();
|
||||
$entity->permissions()->delete();
|
||||
$entity->tags()->delete();
|
||||
$entity->comments()->delete();
|
||||
$this->permissionService->deleteJointPermissionsForEntity($entity);
|
||||
$this->searchService->deleteEntityTerms($entity);
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy the permissions of a bookshelf to all child books.
|
||||
* Returns the number of books that had permissions updated.
|
||||
* @param Bookshelf $bookshelf
|
||||
* @return int
|
||||
* @throws Throwable
|
||||
*/
|
||||
public function copyBookshelfPermissions(Bookshelf $bookshelf)
|
||||
{
|
||||
$shelfPermissions = $bookshelf->permissions()->get(['role_id', 'action'])->toArray();
|
||||
$shelfBooks = $bookshelf->books()->get();
|
||||
$updatedBookCount = 0;
|
||||
|
||||
/** @var Book $book */
|
||||
foreach ($shelfBooks as $book) {
|
||||
if (!userCan('restrictions-manage', $book)) {
|
||||
continue;
|
||||
}
|
||||
$book->permissions()->delete();
|
||||
$book->restricted = $bookshelf->restricted;
|
||||
$book->permissions()->createMany($shelfPermissions);
|
||||
$book->save();
|
||||
$book->rebuildPermissions();
|
||||
$updatedBookCount++;
|
||||
}
|
||||
|
||||
return $updatedBookCount;
|
||||
}
|
||||
}
|
@@ -3,91 +3,199 @@
|
||||
use BookStack\Entities\Book;
|
||||
use BookStack\Entities\Chapter;
|
||||
use BookStack\Entities\Entity;
|
||||
use BookStack\Entities\Managers\BookContents;
|
||||
use BookStack\Entities\Managers\PageContent;
|
||||
use BookStack\Entities\Managers\TrashCan;
|
||||
use BookStack\Entities\Page;
|
||||
use BookStack\Entities\PageRevision;
|
||||
use Carbon\Carbon;
|
||||
use DOMDocument;
|
||||
use DOMElement;
|
||||
use DOMXPath;
|
||||
use BookStack\Exceptions\MoveOperationException;
|
||||
use BookStack\Exceptions\NotFoundException;
|
||||
use BookStack\Exceptions\NotifyException;
|
||||
use BookStack\Exceptions\PermissionsException;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class PageRepo extends EntityRepo
|
||||
class PageRepo
|
||||
{
|
||||
|
||||
protected $baseRepo;
|
||||
|
||||
/**
|
||||
* Get page by slug.
|
||||
* @param string $pageSlug
|
||||
* @param string $bookSlug
|
||||
* @return Page
|
||||
* @throws \BookStack\Exceptions\NotFoundException
|
||||
* PageRepo constructor.
|
||||
*/
|
||||
public function getBySlug(string $pageSlug, string $bookSlug)
|
||||
public function __construct(BaseRepo $baseRepo)
|
||||
{
|
||||
return $this->getEntityBySlug('page', $pageSlug, $bookSlug);
|
||||
$this->baseRepo = $baseRepo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* Get a page by ID.
|
||||
* @throws NotFoundException
|
||||
*/
|
||||
public function getPageByOldSlug(string $pageSlug, string $bookSlug)
|
||||
public function getById(int $id): Page
|
||||
{
|
||||
$revision = $this->entityProvider->pageRevision->where('slug', '=', $pageSlug)
|
||||
->whereHas('page', function ($query) {
|
||||
$this->permissionService->enforceEntityRestrictions('page', $query);
|
||||
$page = Page::visible()->with(['book'])->find($id);
|
||||
|
||||
if (!$page) {
|
||||
throw new NotFoundException(trans('errors.page_not_found'));
|
||||
}
|
||||
|
||||
return $page;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a page its book and own slug.
|
||||
* @throws NotFoundException
|
||||
*/
|
||||
public function getBySlug(string $bookSlug, string $pageSlug): Page
|
||||
{
|
||||
$page = Page::visible()->whereSlugs($bookSlug, $pageSlug)->first();
|
||||
|
||||
if (!$page) {
|
||||
throw new NotFoundException(trans('errors.page_not_found'));
|
||||
}
|
||||
|
||||
return $page;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a page by its old slug but checking the revisions table
|
||||
* for the last revision that matched the given page and book slug.
|
||||
*/
|
||||
public function getByOldSlug(string $bookSlug, string $pageSlug): ?Page
|
||||
{
|
||||
$revision = PageRevision::query()
|
||||
->whereHas('page', function (Builder $query) {
|
||||
$query->visible();
|
||||
})
|
||||
->where('slug', '=', $pageSlug)
|
||||
->where('type', '=', 'version')
|
||||
->where('book_slug', '=', $bookSlug)
|
||||
->orderBy('created_at', 'desc')
|
||||
->with('page')->first();
|
||||
return $revision !== null ? $revision->page : null;
|
||||
->with('page')
|
||||
->first();
|
||||
return $revision ? $revision->page : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* @throws \Exception
|
||||
* Get pages that have been marked as a template.
|
||||
*/
|
||||
public function updatePage(Page $page, int $book_id, array $input)
|
||||
public function getTemplates(int $count = 10, int $page = 1, string $search = ''): LengthAwarePaginator
|
||||
{
|
||||
$query = Page::visible()
|
||||
->where('template', '=', true)
|
||||
->orderBy('name', 'asc')
|
||||
->skip(($page - 1) * $count)
|
||||
->take($count);
|
||||
|
||||
if ($search) {
|
||||
$query->where('name', 'like', '%' . $search . '%');
|
||||
}
|
||||
|
||||
$paginator = $query->paginate($count, ['*'], 'page', $page);
|
||||
$paginator->withPath('/templates');
|
||||
|
||||
return $paginator;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a parent item via slugs.
|
||||
*/
|
||||
public function getParentFromSlugs(string $bookSlug, string $chapterSlug = null): Entity
|
||||
{
|
||||
if ($chapterSlug !== null) {
|
||||
return $chapter = Chapter::visible()->whereSlugs($bookSlug, $chapterSlug)->firstOrFail();
|
||||
}
|
||||
|
||||
return Book::visible()->where('slug', '=', $bookSlug)->firstOrFail();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the draft copy of the given page for the current user.
|
||||
*/
|
||||
public function getUserDraft(Page $page): ?PageRevision
|
||||
{
|
||||
$revision = $this->getUserDraftQuery($page)->first();
|
||||
return $revision;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a new draft page belonging to the given parent entity.
|
||||
*/
|
||||
public function getNewDraftPage(Entity $parent)
|
||||
{
|
||||
$page = (new Page())->forceFill([
|
||||
'name' => trans('entities.pages_initial_name'),
|
||||
'created_by' => user()->id,
|
||||
'updated_by' => user()->id,
|
||||
'draft' => true,
|
||||
]);
|
||||
|
||||
if ($parent instanceof Chapter) {
|
||||
$page->chapter_id = $parent->id;
|
||||
$page->book_id = $parent->book_id;
|
||||
} else {
|
||||
$page->book_id = $parent->id;
|
||||
}
|
||||
|
||||
$page->save();
|
||||
$page->refresh()->rebuildPermissions();
|
||||
return $page;
|
||||
}
|
||||
|
||||
/**
|
||||
* Publish a draft page to make it a live, non-draft page.
|
||||
*/
|
||||
public function publishDraft(Page $draft, array $input): Page
|
||||
{
|
||||
$this->baseRepo->update($draft, $input);
|
||||
if (isset($input['template']) && userCan('templates-manage')) {
|
||||
$draft->template = ($input['template'] === 'true');
|
||||
}
|
||||
|
||||
$pageContent = new PageContent($draft);
|
||||
$pageContent->setNewHTML($input['html']);
|
||||
$draft->draft = false;
|
||||
$draft->revision_count = 1;
|
||||
$draft->priority = $this->getNewPriority($draft);
|
||||
$draft->refreshSlug();
|
||||
$draft->save();
|
||||
|
||||
$this->savePageRevision($draft, trans('entities.pages_initial_revision'));
|
||||
$draft->indexForSearch();
|
||||
return $draft->refresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a page in the system.
|
||||
*/
|
||||
public function update(Page $page, array $input): Page
|
||||
{
|
||||
// Hold the old details to compare later
|
||||
$oldHtml = $page->html;
|
||||
$oldName = $page->name;
|
||||
|
||||
// Save page tags if present
|
||||
if (isset($input['tags'])) {
|
||||
$this->tagRepo->saveTagsToEntity($page, $input['tags']);
|
||||
}
|
||||
|
||||
if (isset($input['template']) && userCan('templates-manage')) {
|
||||
$page->template = ($input['template'] === 'true');
|
||||
}
|
||||
|
||||
$this->baseRepo->update($page, $input);
|
||||
|
||||
// Update with new details
|
||||
$userId = user()->id;
|
||||
$page->fill($input);
|
||||
$page->html = $this->formatHtml($input['html']);
|
||||
$page->text = $this->pageToPlainText($page);
|
||||
$page->updated_by = $userId;
|
||||
$pageContent = new PageContent($page);
|
||||
$pageContent->setNewHTML($input['html']);
|
||||
$page->revision_count++;
|
||||
|
||||
if (setting('app-editor') !== 'markdown') {
|
||||
$page->markdown = '';
|
||||
}
|
||||
|
||||
if ($page->isDirty('name')) {
|
||||
$page->refreshSlug();
|
||||
}
|
||||
|
||||
$page->save();
|
||||
|
||||
// Remove all update drafts for this user & page.
|
||||
$this->userUpdatePageDraftsQuery($page, $userId)->delete();
|
||||
$this->getUserDraftQuery($page)->delete();
|
||||
|
||||
// Save a revision after updating
|
||||
$summary = $input['summary'] ?? null;
|
||||
@@ -95,24 +203,20 @@ class PageRepo extends EntityRepo
|
||||
$this->savePageRevision($page, $summary);
|
||||
}
|
||||
|
||||
$this->searchService->indexEntity($page);
|
||||
|
||||
return $page;
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves a page revision into the system.
|
||||
* @param Page $page
|
||||
* @param null|string $summary
|
||||
* @return PageRevision
|
||||
* @throws \Exception
|
||||
*/
|
||||
public function savePageRevision(Page $page, string $summary = null)
|
||||
protected function savePageRevision(Page $page, string $summary = null)
|
||||
{
|
||||
$revision = $this->entityProvider->pageRevision->newInstance($page->toArray());
|
||||
$revision = new PageRevision($page->toArray());
|
||||
|
||||
if (setting('app-editor') !== 'markdown') {
|
||||
$revision->markdown = '';
|
||||
}
|
||||
|
||||
$revision->page_id = $page->id;
|
||||
$revision->slug = $page->slug;
|
||||
$revision->book_slug = $page->book->slug;
|
||||
@@ -123,163 +227,29 @@ class PageRepo extends EntityRepo
|
||||
$revision->revision_number = $page->revision_count;
|
||||
$revision->save();
|
||||
|
||||
$revisionLimit = config('app.revision_limit');
|
||||
if ($revisionLimit !== false) {
|
||||
$revisionsToDelete = $this->entityProvider->pageRevision->where('page_id', '=', $page->id)
|
||||
->orderBy('created_at', 'desc')->skip(intval($revisionLimit))->take(10)->get(['id']);
|
||||
if ($revisionsToDelete->count() > 0) {
|
||||
$this->entityProvider->pageRevision->whereIn('id', $revisionsToDelete->pluck('id'))->delete();
|
||||
}
|
||||
}
|
||||
|
||||
$this->deleteOldRevisions($page);
|
||||
return $revision;
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats a page's html to be tagged correctly within the system.
|
||||
* @param string $htmlText
|
||||
* @return string
|
||||
*/
|
||||
protected function formatHtml(string $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;
|
||||
|
||||
// Set ids on top-level nodes
|
||||
$idMap = [];
|
||||
foreach ($childNodes as $index => $childNode) {
|
||||
$this->setUniqueId($childNode, $idMap);
|
||||
}
|
||||
|
||||
// Ensure no duplicate ids within child items
|
||||
$xPath = new DOMXPath($doc);
|
||||
$idElems = $xPath->query('//body//*//*[@id]');
|
||||
foreach ($idElems as $domElem) {
|
||||
$this->setUniqueId($domElem, $idMap);
|
||||
}
|
||||
|
||||
// Generate inner html as a string
|
||||
$html = '';
|
||||
foreach ($childNodes as $childNode) {
|
||||
$html .= $doc->saveHTML($childNode);
|
||||
}
|
||||
|
||||
return $html;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a unique id on the given DOMElement.
|
||||
* A map for existing ID's should be passed in to check for current existence.
|
||||
* @param DOMElement $element
|
||||
* @param array $idMap
|
||||
*/
|
||||
protected function setUniqueId($element, array &$idMap)
|
||||
{
|
||||
if (get_class($element) !== 'DOMElement') {
|
||||
return;
|
||||
}
|
||||
|
||||
// Overwrite id if not a BookStack custom id
|
||||
$existingId = $element->getAttribute('id');
|
||||
if (strpos($existingId, 'bkmrk') === 0 && !isset($idMap[$existingId])) {
|
||||
$idMap[$existingId] = true;
|
||||
return;
|
||||
}
|
||||
|
||||
// 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-' . mb_substr(strtolower(preg_replace('/\s+/', '-', trim($element->nodeValue))), 0, 20);
|
||||
$newId = urlencode($contentId);
|
||||
$loopIndex = 0;
|
||||
|
||||
while (isset($idMap[$newId])) {
|
||||
$newId = urlencode($contentId . '-' . $loopIndex);
|
||||
$loopIndex++;
|
||||
}
|
||||
|
||||
$element->setAttribute('id', $newId);
|
||||
$idMap[$newId] = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the plain text version of a page's content.
|
||||
* @param \BookStack\Entities\Page $page
|
||||
* @return string
|
||||
*/
|
||||
protected function pageToPlainText(Page $page) : string
|
||||
{
|
||||
$html = $this->renderPage($page, true);
|
||||
return strip_tags($html);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a new draft page instance.
|
||||
* @param Book $book
|
||||
* @param Chapter|null $chapter
|
||||
* @return \BookStack\Entities\Page
|
||||
* @throws \Throwable
|
||||
*/
|
||||
public function getDraftPage(Book $book, Chapter $chapter = null)
|
||||
{
|
||||
$page = $this->entityProvider->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);
|
||||
$page->refresh()->rebuildPermissions();
|
||||
return $page;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save a page update draft.
|
||||
* @param Page $page
|
||||
* @param array $data
|
||||
* @return PageRevision|Page
|
||||
*/
|
||||
public function updatePageDraft(Page $page, array $data = [])
|
||||
public function updatePageDraft(Page $page, array $input)
|
||||
{
|
||||
// If the page itself is a draft simply update that
|
||||
if ($page->draft) {
|
||||
$page->fill($data);
|
||||
if (isset($data['html'])) {
|
||||
$page->text = $this->pageToPlainText($page);
|
||||
$page->fill($input);
|
||||
if (isset($input['html'])) {
|
||||
$content = new PageContent($page);
|
||||
$content->setNewHTML($input['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->entityProvider->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);
|
||||
$draft = $this->getPageRevisionToUpdate($page);
|
||||
$draft->fill($input);
|
||||
if (setting('app-editor') !== 'markdown') {
|
||||
$draft->markdown = '';
|
||||
}
|
||||
@@ -289,227 +259,76 @@ class PageRepo extends EntityRepo
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* @throws \Exception
|
||||
* Destroy a page from the system.
|
||||
* @throws NotifyException
|
||||
*/
|
||||
public function publishPageDraft(Page $draftPage, array $input)
|
||||
public function destroy(Page $page)
|
||||
{
|
||||
$draftPage->fill($input);
|
||||
|
||||
// Save page tags if present
|
||||
if (isset($input['tags'])) {
|
||||
$this->tagRepo->saveTagsToEntity($draftPage, $input['tags']);
|
||||
}
|
||||
|
||||
if (isset($input['template']) && userCan('templates-manage')) {
|
||||
$draftPage->template = ($input['template'] === 'true');
|
||||
}
|
||||
|
||||
$draftPage->html = $this->formatHtml($input['html']);
|
||||
$draftPage->text = $this->pageToPlainText($draftPage);
|
||||
$draftPage->draft = false;
|
||||
$draftPage->revision_count = 1;
|
||||
$draftPage->refreshSlug();
|
||||
$draftPage->save();
|
||||
$this->savePageRevision($draftPage, trans('entities.pages_initial_revision'));
|
||||
$this->searchService->indexEntity($draftPage);
|
||||
return $draftPage;
|
||||
}
|
||||
|
||||
/**
|
||||
* The base query for getting user update drafts.
|
||||
* @param Page $page
|
||||
* @param $userId
|
||||
* @return mixed
|
||||
*/
|
||||
protected function userUpdatePageDraftsQuery(Page $page, int $userId)
|
||||
{
|
||||
return $this->entityProvider->pageRevision->where('created_by', '=', $userId)
|
||||
->where('type', 'update_draft')
|
||||
->where('page_id', '=', $page->id)
|
||||
->orderBy('created_at', 'desc');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the latest updated draft revision for a particular page and user.
|
||||
* @param Page $page
|
||||
* @param $userId
|
||||
* @return PageRevision|null
|
||||
*/
|
||||
public function getUserPageDraft(Page $page, int $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');
|
||||
}
|
||||
|
||||
/**
|
||||
* A query to check for active update drafts on a particular page.
|
||||
* @param Page $page
|
||||
* @param int $minRange
|
||||
* @return mixed
|
||||
*/
|
||||
protected function activePageEditingQuery(Page $page, int $minRange = null)
|
||||
{
|
||||
$query = $this->entityProvider->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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 int $minRange
|
||||
* @return bool
|
||||
*/
|
||||
public function isPageEditingActive(Page $page, int $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 int $minRange
|
||||
* @return string
|
||||
*/
|
||||
public function getPageEditingActiveMessage(Page $page, int $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]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the headers on the page to get a navigation menu
|
||||
* @param string $pageContent
|
||||
* @return array
|
||||
*/
|
||||
public function getPageNav(string $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($headers)->map(function ($header) {
|
||||
$text = trim(str_replace("\xc2\xa0", '', $header->nodeValue));
|
||||
$text = mb_substr($text, 0, 100);
|
||||
|
||||
return [
|
||||
'nodeName' => strtolower($header->nodeName),
|
||||
'level' => intval(str_replace('h', '', $header->nodeName)),
|
||||
'link' => '#' . $header->getAttribute('id'),
|
||||
'text' => $text,
|
||||
];
|
||||
})->filter(function ($header) {
|
||||
return mb_strlen($header['text']) > 0;
|
||||
});
|
||||
|
||||
// Shift headers if only smaller headers have been used
|
||||
$levelChange = ($tree->pluck('level')->min() - 1);
|
||||
$tree = $tree->map(function ($header) use ($levelChange) {
|
||||
$header['level'] -= ($levelChange);
|
||||
return $header;
|
||||
});
|
||||
|
||||
return $tree->toArray();
|
||||
$trashCan = new TrashCan();
|
||||
$trashCan->destroyPage($page);
|
||||
}
|
||||
|
||||
/**
|
||||
* Restores a revision's content back into a page.
|
||||
* @param Page $page
|
||||
* @param Book $book
|
||||
* @param int $revisionId
|
||||
* @return Page
|
||||
* @throws \Exception
|
||||
*/
|
||||
public function restorePageRevision(Page $page, Book $book, int $revisionId)
|
||||
public function restoreRevision(Page $page, int $revisionId): Page
|
||||
{
|
||||
$page->revision_count++;
|
||||
$this->savePageRevision($page);
|
||||
|
||||
$revision = $page->revisions()->where('id', '=', $revisionId)->first();
|
||||
$page->fill($revision->toArray());
|
||||
$page->text = $this->pageToPlainText($page);
|
||||
$content = new PageContent($page);
|
||||
$content->setNewHTML($page->html);
|
||||
$page->updated_by = user()->id;
|
||||
$page->refreshSlug();
|
||||
$page->save();
|
||||
|
||||
$this->searchService->indexEntity($page);
|
||||
$page->indexForSearch();
|
||||
return $page;
|
||||
}
|
||||
|
||||
/**
|
||||
* Change the page's parent to the given entity.
|
||||
* @param Page $page
|
||||
* @param Entity $parent
|
||||
* Move the given page into a new parent book or chapter.
|
||||
* The $parentIdentifier must be a string of the following format:
|
||||
* 'book:<id>' (book:5)
|
||||
* @throws MoveOperationException
|
||||
* @throws PermissionsException
|
||||
*/
|
||||
public function changePageParent(Page $page, Entity $parent)
|
||||
public function move(Page $page, string $parentIdentifier): Book
|
||||
{
|
||||
$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);
|
||||
$parent = $this->findParentByIdentifier($parentIdentifier);
|
||||
if ($parent === null) {
|
||||
throw new MoveOperationException('Book or chapter to move page into not found');
|
||||
}
|
||||
|
||||
$page->load('book');
|
||||
$book->rebuildPermissions();
|
||||
if (!userCan('page-create', $parent)) {
|
||||
throw new PermissionsException('User does not have permission to create a page within the new parent');
|
||||
}
|
||||
|
||||
$page->changeBook($parent instanceof Book ? $parent->id : $parent->book->id);
|
||||
$page->rebuildPermissions();
|
||||
return $parent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a copy of a page in a new location with a new name.
|
||||
* @param \BookStack\Entities\Page $page
|
||||
* @param \BookStack\Entities\Entity $newParent
|
||||
* @param string $newName
|
||||
* @return \BookStack\Entities\Page
|
||||
* @throws \Throwable
|
||||
* Copy an existing page in the system.
|
||||
* Optionally providing a new parent via string identifier and a new name.
|
||||
* @throws MoveOperationException
|
||||
* @throws PermissionsException
|
||||
*/
|
||||
public function copyPage(Page $page, Entity $newParent, string $newName = '')
|
||||
public function copy(Page $page, string $parentIdentifier = null, string $newName = null): Page
|
||||
{
|
||||
$newBook = $newParent->isA('book') ? $newParent : $newParent->book;
|
||||
$newChapter = $newParent->isA('chapter') ? $newParent : null;
|
||||
$copyPage = $this->getDraftPage($newBook, $newChapter);
|
||||
$parent = $parentIdentifier ? $this->findParentByIdentifier($parentIdentifier) : $page->parent();
|
||||
if ($parent === null) {
|
||||
throw new MoveOperationException('Book or chapter to move page into not found');
|
||||
}
|
||||
|
||||
if (!userCan('page-create', $parent)) {
|
||||
throw new PermissionsException('User does not have permission to create a page within the new parent');
|
||||
}
|
||||
|
||||
$copyPage = $this->getNewDraftPage($parent);
|
||||
$pageData = $page->getAttributes();
|
||||
|
||||
// Update name
|
||||
@@ -525,38 +344,116 @@ class PageRepo extends EntityRepo
|
||||
}
|
||||
}
|
||||
|
||||
// Set priority
|
||||
if ($newParent->isA('chapter')) {
|
||||
$pageData['priority'] = $this->getNewChapterPriority($newParent);
|
||||
} else {
|
||||
$pageData['priority'] = $this->getNewBookPriority($newParent);
|
||||
}
|
||||
|
||||
return $this->publishPageDraft($copyPage, $pageData);
|
||||
return $this->publishDraft($copyPage, $pageData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get pages that have been marked as templates.
|
||||
* @param int $count
|
||||
* @param int $page
|
||||
* @param string $search
|
||||
* @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
|
||||
* Find a page parent entity via a identifier string in the format:
|
||||
* {type}:{id}
|
||||
* Example: (book:5)
|
||||
* @throws MoveOperationException
|
||||
*/
|
||||
public function getPageTemplates(int $count = 10, int $page = 1, string $search = '')
|
||||
protected function findParentByIdentifier(string $identifier): ?Entity
|
||||
{
|
||||
$query = $this->entityQuery('page')
|
||||
->where('template', '=', true)
|
||||
->orderBy('name', 'asc')
|
||||
->skip(($page - 1) * $count)
|
||||
->take($count);
|
||||
$stringExploded = explode(':', $identifier);
|
||||
$entityType = $stringExploded[0];
|
||||
$entityId = intval($stringExploded[1]);
|
||||
|
||||
if ($search) {
|
||||
$query->where('name', 'like', '%' . $search . '%');
|
||||
if ($entityType !== 'book' && $entityType !== 'chapter') {
|
||||
throw new MoveOperationException('Pages can only be in books or chapters');
|
||||
}
|
||||
|
||||
$paginator = $query->paginate($count, ['*'], 'page', $page);
|
||||
$paginator->withPath('/templates');
|
||||
$parentClass = $entityType === 'book' ? Book::class : Chapter::class;
|
||||
return $parentClass::visible()->where('id', '=', $entityId)->first();
|
||||
}
|
||||
|
||||
return $paginator;
|
||||
/**
|
||||
* Update the permissions of a page.
|
||||
*/
|
||||
public function updatePermissions(Page $page, bool $restricted, Collection $permissions = null)
|
||||
{
|
||||
$this->baseRepo->updatePermissions($page, $restricted, $permissions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Change the page's parent to the given entity.
|
||||
*/
|
||||
protected function changeParent(Page $page, Entity $parent)
|
||||
{
|
||||
$book = ($parent instanceof Book) ? $parent : $parent->book;
|
||||
$page->chapter_id = ($parent instanceof Chapter) ? $parent->id : 0;
|
||||
$page->save();
|
||||
|
||||
if ($page->book->id !== $book->id) {
|
||||
$page->changeBook($book->id);
|
||||
}
|
||||
|
||||
$page->load('book');
|
||||
$book->rebuildPermissions();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a page revision to update for the given page.
|
||||
* Checks for an existing revisions before providing a fresh one.
|
||||
*/
|
||||
protected function getPageRevisionToUpdate(Page $page): PageRevision
|
||||
{
|
||||
$drafts = $this->getUserDraftQuery($page)->get();
|
||||
if ($drafts->count() > 0) {
|
||||
return $drafts->first();
|
||||
}
|
||||
|
||||
$draft = new PageRevision();
|
||||
$draft->page_id = $page->id;
|
||||
$draft->slug = $page->slug;
|
||||
$draft->book_slug = $page->book->slug;
|
||||
$draft->created_by = user()->id;
|
||||
$draft->type = 'update_draft';
|
||||
return $draft;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete old revisions, for the given page, from the system.
|
||||
*/
|
||||
protected function deleteOldRevisions(Page $page)
|
||||
{
|
||||
$revisionLimit = config('app.revision_limit');
|
||||
if ($revisionLimit === false) {
|
||||
return;
|
||||
}
|
||||
|
||||
$revisionsToDelete = PageRevision::query()
|
||||
->where('page_id', '=', $page->id)
|
||||
->orderBy('created_at', 'desc')
|
||||
->skip(intval($revisionLimit))
|
||||
->take(10)
|
||||
->get(['id']);
|
||||
if ($revisionsToDelete->count() > 0) {
|
||||
PageRevision::query()->whereIn('id', $revisionsToDelete->pluck('id'))->delete();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a new priority for a page
|
||||
*/
|
||||
protected function getNewPriority(Page $page): int
|
||||
{
|
||||
if ($page->parent() instanceof Chapter) {
|
||||
$lastPage = $page->parent()->pages('desc')->first();
|
||||
return $lastPage ? $lastPage->priority + 1 : 0;
|
||||
}
|
||||
|
||||
return (new BookContents($page->book))->getLastPriority() + 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the query to find the user's draft copies of the given page.
|
||||
*/
|
||||
protected function getUserDraftQuery(Page $page)
|
||||
{
|
||||
return PageRevision::query()->where('created_by', '=', user()->id)
|
||||
->where('type', 'update_draft')
|
||||
->where('page_id', '=', $page->id)
|
||||
->orderBy('created_at', 'desc');
|
||||
}
|
||||
}
|
||||
|
@@ -59,6 +59,4 @@ class SlugGenerator
|
||||
|
||||
return $query->count() > 0;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user