1
0
mirror of https://github.com/BookStackApp/BookStack.git synced 2025-08-09 10:22:51 +03:00

Revamped image system to use driver-agnotstic storage and be more efficent

This commit is contained in:
Dan Brown
2015-12-07 23:00:34 +00:00
parent 46c905df8a
commit c88096b7e2
12 changed files with 557 additions and 144 deletions

View File

@@ -2,6 +2,7 @@
namespace BookStack\Http\Controllers;
use BookStack\Repos\ImageRepo;
use Illuminate\Filesystem\Filesystem as File;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
@@ -14,16 +15,19 @@ class ImageController extends Controller
{
protected $image;
protected $file;
protected $imageRepo;
/**
* ImageController constructor.
* @param Image $image
* @param File $file
* @param Image $image
* @param File $file
* @param ImageRepo $imageRepo
*/
public function __construct(Image $image, File $file)
public function __construct(Image $image, File $file, ImageRepo $imageRepo)
{
$this->image = $image;
$this->file = $file;
$this->imageRepo = $imageRepo;
parent::__construct();
}
@@ -33,108 +37,31 @@ class ImageController extends Controller
* @param int $page
* @return \Illuminate\Http\JsonResponse
*/
public function getAll($page = 0)
public function getAllGallery($page = 0)
{
$pageSize = 30;
$images = $this->image->orderBy('created_at', 'desc')
->skip($page * $pageSize)->take($pageSize)->get();
foreach ($images as $image) {
$this->loadSizes($image);
}
$hasMore = $this->image->orderBy('created_at', 'desc')
->skip(($page + 1) * $pageSize)->take($pageSize)->count() > 0;
return response()->json([
'images' => $images,
'hasMore' => $hasMore
]);
$imgData = $this->imageRepo->getAllGallery($page);
return response()->json($imgData);
}
/**
* Loads the standard thumbnail sizes for an image.
* @param Image $image
*/
private function loadSizes(Image $image)
{
$image->thumbnail = $this->getThumbnail($image, 150, 150);
$image->display = $this->getThumbnail($image, 840, 0, true);
}
/**
* Get the thumbnail for an image.
* If $keepRatio is true only the width will be used.
* @param $image
* @param int $width
* @param int $height
* @param bool $keepRatio
* @return string
*/
public function getThumbnail($image, $width = 220, $height = 220, $keepRatio = false)
{
$explodedPath = explode('/', $image->url);
$dirPrefix = $keepRatio ? 'scaled-' : 'thumbs-';
array_splice($explodedPath, 4, 0, [$dirPrefix . $width . '-' . $height]);
$thumbPath = implode('/', $explodedPath);
$thumbFilePath = public_path() . $thumbPath;
// Return the thumbnail url path if already exists
if (file_exists($thumbFilePath)) {
return $thumbPath;
}
// Otherwise create the thumbnail
$thumb = ImageTool::make(public_path() . $image->url);
if($keepRatio) {
$thumb->resize($width, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
} else {
$thumb->fit($width, $height);
}
// Create thumbnail folder if it does not exist
if (!file_exists(dirname($thumbFilePath))) {
mkdir(dirname($thumbFilePath), 0775, true);
}
//Save Thumbnail
$thumb->save($thumbFilePath);
return $thumbPath;
}
/**
* Handles image uploads for use on pages.
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function upload(Request $request)
public function uploadGallery(Request $request)
{
$this->checkPermission('image-create');
$this->validate($request, [
'file' => 'image|mimes:jpeg,gif,png'
]);
$imageUpload = $request->file('file');
$name = str_replace(' ', '-', $imageUpload->getClientOriginalName());
$storageName = substr(sha1(time()), 0, 10) . '-' . $name;
$imagePath = '/uploads/images/' . Date('Y-m-M') . '/';
$storagePath = public_path() . $imagePath;
$fullPath = $storagePath . $storageName;
while (file_exists($fullPath)) {
$storageName = substr(sha1(rand()), 0, 3) . $storageName;
$fullPath = $storagePath . $storageName;
}
$imageUpload->move($storagePath, $storageName);
// Create and save image object
$this->image->name = $name;
$this->image->url = $imagePath . $storageName;
$this->image->created_by = auth()->user()->id;
$this->image->updated_by = auth()->user()->id;
$this->image->save();
$this->loadSizes($this->image);
return response()->json($this->image);
$imageUpload = $request->file('file');
$image = $this->imageRepo->saveNew($imageUpload, 'gallery');
return response()->json($image);
}
/**
* Update image details
* @param $imageId
@@ -147,13 +74,12 @@ class ImageController extends Controller
$this->validate($request, [
'name' => 'required|min:2|string'
]);
$image = $this->image->findOrFail($imageId);
$image->fill($request->all());
$image->save();
$this->loadSizes($image);
return response()->json($this->image);
$image = $this->imageRepo->getById($imageId);
$image = $this->imageRepo->updateImageDetails($image, $request->all());
return response()->json($image);
}
/**
* Deletes an image and all thumbnail/image files
* @param PageRepo $pageRepo
@@ -164,41 +90,18 @@ class ImageController extends Controller
public function destroy(PageRepo $pageRepo, Request $request, $id)
{
$this->checkPermission('image-delete');
$image = $this->image->findOrFail($id);
$image = $this->imageRepo->getById($id);
// Check if this image is used on any pages
$pageSearch = $pageRepo->searchForImage($image->url);
$isForced = ($request->has('force') && ($request->get('force') === 'true') || $request->get('force') === true);
if ($pageSearch !== false && !$isForced) {
return response()->json($pageSearch, 400);
}
// Delete files
$folder = public_path() . dirname($image->url);
$fileName = basename($image->url);
// Delete thumbnails
foreach (glob($folder . '/*') as $file) {
if (is_dir($file)) {
$thumbName = $file . '/' . $fileName;
if (file_exists($file)) {
unlink($thumbName);
}
// Remove thumb folder if empty
if (count(glob($file . '/*')) === 0) {
rmdir($file);
}
if (!$isForced) {
$pageSearch = $pageRepo->searchForImage($image->url);
if ($pageSearch !== false) {
return response()->json($pageSearch, 400);
}
}
// Delete file and database entry
unlink($folder . '/' . $fileName);
$image->delete();
// Delete parent folder if empty
if (count(glob($folder . '/*')) === 0) {
rmdir($folder);
}
$this->imageRepo->destroyImage($image);
return response()->json('Image Deleted');
}

View File

@@ -45,8 +45,6 @@ Route::group(['middleware' => 'auth'], function () {
});
// Uploads
Route::post('/upload/image', 'ImageController@upload');
// Users
Route::get('/users', 'UserController@index');
@@ -58,10 +56,13 @@ Route::group(['middleware' => 'auth'], function () {
Route::delete('/users/{id}', 'UserController@destroy');
// Image routes
Route::get('/images/all', 'ImageController@getAll');
Route::put('/images/update/{imageId}', 'ImageController@update');
Route::delete('/images/{imageId}', 'ImageController@destroy');
Route::get('/images/all/{page}', 'ImageController@getAll');
Route::group(['prefix' => 'images'], function() {
Route::get('/gallery/all', 'ImageController@getAllGallery');
Route::get('/gallery/all/{page}', 'ImageController@getAllGallery');
Route::post('/gallery/upload', 'ImageController@uploadGallery');
Route::put('/update/{imageId}', 'ImageController@update');
Route::delete('/{imageId}', 'ImageController@destroy');
});
// Links
Route::get('/link/{id}', 'PageController@redirectFromLink');

View File

@@ -77,6 +77,12 @@ class BookRepo
return Views::getUserRecentlyViewed($count, $page, $this->book);
}
/**
* Gets the most viewed books.
* @param int $count
* @param int $page
* @return mixed
*/
public function getPopular($count = 10, $page = 0)
{
return Views::getPopular($count, $page, $this->book);

265
app/Repos/ImageRepo.php Normal file
View File

@@ -0,0 +1,265 @@
<?php namespace BookStack\Repos;
use BookStack\Image;
use Illuminate\Contracts\Filesystem\Filesystem as FileSystemInstance;
use Intervention\Image\ImageManager as ImageTool;
use Illuminate\Contracts\Filesystem\Factory as FileSystem;
use Illuminate\Contracts\Cache\Repository as Cache;
use Setting;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class ImageRepo
{
protected $image;
protected $imageTool;
protected $fileSystem;
protected $cache;
/**
* @var FileSystemInstance
*/
protected $storageInstance;
protected $storageUrl;
/**
* ImageRepo constructor.
* @param Image $image
* @param ImageTool $imageTool
* @param FileSystem $fileSystem
* @param Cache $cache
*/
public function __construct(Image $image, ImageTool $imageTool, FileSystem $fileSystem, Cache $cache)
{
$this->image = $image;
$this->imageTool = $imageTool;
$this->fileSystem = $fileSystem;
$this->cache = $cache;
}
/**
* Get an image with the given id.
* @param $id
* @return mixed
*/
public function getById($id)
{
return $this->image->findOrFail($id);
}
/**
* Get all images for the standard gallery view that's used for
* adding images to shared content such as pages.
* @param int $page
* @param int $pageSize
* @return array
*/
public function getAllGallery($page = 0, $pageSize = 24)
{
$images = $this->image->where('type', '=', 'gallery')
->orderBy('created_at', 'desc')->skip($pageSize * $page)->take($pageSize + 1)->get();
$hasMore = count($images) > $pageSize;
$returnImages = $images->take(24);
$returnImages->each(function ($image) {
$this->loadThumbs($image);
});
return [
'images' => $returnImages,
'hasMore' => $hasMore
];
}
/**
* Save a new image into storage and return the new image.
* @param UploadedFile $uploadFile
* @param string $type
* @return Image
*/
public function saveNew(UploadedFile $uploadFile, $type)
{
$storage = $this->getStorage();
$secureUploads = Setting::get('app-secure-images');
$imageName = str_replace(' ', '-', $uploadFile->getClientOriginalName());
if ($secureUploads) $imageName = str_random(16) . '-' . $imageName;
$imagePath = '/uploads/images/' . $type . '/' . Date('Y-m-M') . '/';
while ($storage->exists($imagePath . $imageName)) {
$imageName = str_random(3) . $imageName;
}
$fullPath = $imagePath . $imageName;
$storage->put($fullPath, file_get_contents($uploadFile->getRealPath()));
$userId = auth()->user()->id;
$image = $this->image->forceCreate([
'name' => $imageName,
'path' => $fullPath,
'url' => $this->getPublicUrl($fullPath),
'type' => $type,
'created_by' => $userId,
'updated_by' => $userId
]);
$this->loadThumbs($image);
return $image;
}
/**
* Update the details of an image via an array of properties.
* @param Image $image
* @param array $updateDetails
* @return Image
*/
public function updateImageDetails(Image $image, $updateDetails)
{
$image->fill($updateDetails);
$image->save();
$this->loadThumbs($image);
return $image;
}
/**
* Destroys an Image object along with its files and thumbnails.
* @param Image $image
* @return bool
*/
public function destroyImage(Image $image)
{
$storage = $this->getStorage();
$imageFolder = dirname($image->path);
$imageFileName = basename($image->path);
$allImages = collect($storage->allFiles($imageFolder));
$imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
$expectedIndex = strlen($imagePath) - strlen($imageFileName);
return strpos($imagePath, $imageFileName) === $expectedIndex;
});
$storage->delete($imagesToDelete->all());
// Cleanup of empty folders
foreach ($storage->directories($imageFolder) as $directory) {
if ($this->isFolderEmpty($directory)) $storage->deleteDirectory($directory);
}
if ($this->isFolderEmpty($imageFolder)) $storage->deleteDirectory($imageFolder);
$image->delete();
return true;
}
/**
* Check whether or not a folder is empty.
* @param $path
* @return int
*/
private function isFolderEmpty($path)
{
$files = $this->getStorage()->files($path);
$folders = $this->getStorage()->directories($path);
return count($files) === 0 && count($folders) === 0;
}
/**
* Load thumbnails onto an image object.
* @param Image $image
*/
private function loadThumbs(Image $image)
{
$image->thumbs = [
'gallery' => $this->getThumbnail($image, 150, 150),
'display' => $this->getThumbnail($image, 840, 0, true)
];
}
/**
* Get the thumbnail for an image.
* If $keepRatio is true only the width will be used.
* Checks the cache then storage to avoid creating / accessing the filesystem on every check.
*
* @param Image $image
* @param int $width
* @param int $height
* @param bool $keepRatio
* @return string
*/
private function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
{
$thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
$thumbFilePath = dirname($image->path) . $thumbDirName . basename($image->path);
if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
return $this->getPublicUrl($thumbFilePath);
}
$storage = $this->getStorage();
if ($storage->exists($thumbFilePath)) {
return $this->getPublicUrl($thumbFilePath);
}
// Otherwise create the thumbnail
$thumb = $this->imageTool->make($storage->get($image->path));
if ($keepRatio) {
$thumb->resize($width, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
} else {
$thumb->fit($width, $height);
}
$thumbData = (string)$thumb->encode();
$storage->put($thumbFilePath, $thumbData);
$this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 72);
return $this->getPublicUrl($thumbFilePath);
}
/**
* Gets a public facing url for an image by checking relevant environment variables.
* @param $filePath
* @return string
*/
private function getPublicUrl($filePath)
{
if ($this->storageUrl === null) {
$storageUrl = env('STORAGE_URL');
// Get the standard public s3 url if s3 is set as storage type
if ($storageUrl == false && env('STORAGE_TYPE') === 's3') {
$storageDetails = config('filesystems.disks.s3');
$storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'] . $filePath;
}
$this->storageUrl = $storageUrl;
}
return ($this->storageUrl == false ? '' : rtrim($this->storageUrl, '/')) . $filePath;
}
/**
* Get the storage that will be used for storing images.
* @return FileSystemInstance
*/
private function getStorage()
{
if ($this->storageInstance !== null) return $this->storageInstance;
$storageType = env('STORAGE_TYPE');
$this->storageInstance = $this->fileSystem->disk($storageType);
return $this->storageInstance;
}
}