mirror of
https://github.com/BookStackApp/BookStack.git
synced 2025-11-07 12:26:22 +03:00
As per PR #5800 * DB: Planned out new entity table format via migrations * DB: Created entity migration logic Made some other tweaks/fixes while testing. * DB: Added change of entity relation columns to suit new entities table * DB: Got most view queries working for new structure * Entities: Started logic change to new structure Updated base entity class, and worked through BaseRepo. Need to go through other repos next. Removed a couple of redundant interfaces as part of this since we can move the logic onto the shared ContainerData model as needed. * Entities: Been through repos to update for new format * Entities: Updated repos to act on refreshed clones Changes to core entity models are now done on clones to ensure clean state before save, and those clones are returned back if changes are needed after that action. * Entities: Updated model classes & relations for changes * Entities: Changed from *Data to a common "contents" system Added smart loading from builder instances which should hydrate with "contents()" loaded via join, while keeping the core model original. * Entities: Moved entity description/covers to own non-model classes Added back some interfaces. * Entities: Removed use of contents system for data access * Entities: Got most queries back to working order * Entities: Reverted back to data from contents, fixed various issues * Entities: Started addressing issues from tests * Entities: Addressed further tests/issues * Entities: Been through tests to get all passing in dev Fixed issues and needed test changes along the way. * Entities: Addressed phpstan errors * Entities: Reviewed TODO notes * Entities: Ensured book/shelf relation data removed on destroy * Entities: Been through API responses & adjusted field visibility * Entities: Added type index to massively improve query speed
190 lines
6.8 KiB
PHP
190 lines
6.8 KiB
PHP
<?php
|
|
|
|
namespace BookStack\Uploads\Controllers;
|
|
|
|
use BookStack\Entities\EntityExistsRule;
|
|
use BookStack\Entities\Queries\PageQueries;
|
|
use BookStack\Exceptions\FileUploadException;
|
|
use BookStack\Http\ApiController;
|
|
use BookStack\Permissions\Permission;
|
|
use BookStack\Uploads\Attachment;
|
|
use BookStack\Uploads\AttachmentService;
|
|
use Exception;
|
|
use Illuminate\Contracts\Filesystem\FileNotFoundException;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Validation\ValidationException;
|
|
|
|
class AttachmentApiController extends ApiController
|
|
{
|
|
public function __construct(
|
|
protected AttachmentService $attachmentService,
|
|
protected PageQueries $pageQueries,
|
|
) {
|
|
}
|
|
|
|
/**
|
|
* Get a listing of attachments visible to the user.
|
|
* The external property indicates whether the attachment is simple a link.
|
|
* A false value for the external property would indicate a file upload.
|
|
*/
|
|
public function list()
|
|
{
|
|
return $this->apiListingResponse(Attachment::visible(), [
|
|
'id', 'name', 'extension', 'uploaded_to', 'external', 'order', 'created_at', 'updated_at', 'created_by', 'updated_by',
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* Create a new attachment in the system.
|
|
* An uploaded_to value must be provided containing an ID of the page
|
|
* that this upload will be related to.
|
|
*
|
|
* If you're uploading a file the POST data should be provided via
|
|
* a multipart/form-data type request instead of JSON.
|
|
*
|
|
* @throws ValidationException
|
|
* @throws FileUploadException
|
|
*/
|
|
public function create(Request $request)
|
|
{
|
|
$this->checkPermission(Permission::AttachmentCreateAll);
|
|
$requestData = $this->validate($request, $this->rules()['create']);
|
|
|
|
$pageId = $request->get('uploaded_to');
|
|
$page = $this->pageQueries->findVisibleByIdOrFail($pageId);
|
|
$this->checkOwnablePermission(Permission::PageUpdate, $page);
|
|
|
|
if ($request->hasFile('file')) {
|
|
$uploadedFile = $request->file('file');
|
|
$attachment = $this->attachmentService->saveNewUpload($uploadedFile, $page->id);
|
|
} else {
|
|
$attachment = $this->attachmentService->saveNewFromLink(
|
|
$requestData['name'],
|
|
$requestData['link'],
|
|
$page->id
|
|
);
|
|
}
|
|
|
|
$this->attachmentService->updateFile($attachment, $requestData);
|
|
|
|
return response()->json($attachment);
|
|
}
|
|
|
|
/**
|
|
* Get the details & content of a single attachment of the given ID.
|
|
* The attachment link or file content is provided via a 'content' property.
|
|
* For files the content will be base64 encoded.
|
|
*
|
|
* @throws FileNotFoundException
|
|
*/
|
|
public function read(string $id)
|
|
{
|
|
/** @var Attachment $attachment */
|
|
$attachment = Attachment::visible()
|
|
->with(['createdBy', 'updatedBy'])
|
|
->findOrFail($id);
|
|
|
|
$attachment->setAttribute('links', [
|
|
'html' => $attachment->htmlLink(),
|
|
'markdown' => $attachment->markdownLink(),
|
|
]);
|
|
|
|
// Simply return a JSON response of the attachment for link-based attachments
|
|
if ($attachment->external) {
|
|
$attachment->setAttribute('content', $attachment->path);
|
|
|
|
return response()->json($attachment);
|
|
}
|
|
|
|
// Build and split our core JSON, at point of content.
|
|
$splitter = 'CONTENT_SPLIT_LOCATION_' . time() . '_' . rand(1, 40000);
|
|
$attachment->setAttribute('content', $splitter);
|
|
$json = $attachment->toJson();
|
|
$jsonParts = explode($splitter, $json);
|
|
// Get a stream for the file data from storage
|
|
$stream = $this->attachmentService->streamAttachmentFromStorage($attachment);
|
|
|
|
return response()->stream(function () use ($jsonParts, $stream) {
|
|
// Output the pre-content JSON data
|
|
echo $jsonParts[0];
|
|
|
|
// Stream out our attachment data as base64 content
|
|
stream_filter_append($stream, 'convert.base64-encode', STREAM_FILTER_READ);
|
|
fpassthru($stream);
|
|
fclose($stream);
|
|
|
|
// Output our post-content JSON data
|
|
echo $jsonParts[1];
|
|
}, 200, ['Content-Type' => 'application/json']);
|
|
}
|
|
|
|
/**
|
|
* Update the details of a single attachment.
|
|
* As per the create endpoint, if a file is being provided as the attachment content
|
|
* the request should be formatted as a multipart/form-data request instead of JSON.
|
|
*
|
|
* @throws ValidationException
|
|
* @throws FileUploadException
|
|
*/
|
|
public function update(Request $request, string $id)
|
|
{
|
|
$requestData = $this->validate($request, $this->rules()['update']);
|
|
/** @var Attachment $attachment */
|
|
$attachment = Attachment::visible()->findOrFail($id);
|
|
|
|
$page = $attachment->page;
|
|
if ($requestData['uploaded_to'] ?? false) {
|
|
$pageId = $request->get('uploaded_to');
|
|
$page = $this->pageQueries->findVisibleByIdOrFail($pageId);
|
|
$attachment->uploaded_to = $requestData['uploaded_to'];
|
|
}
|
|
|
|
$this->checkOwnablePermission(Permission::PageView, $page);
|
|
$this->checkOwnablePermission(Permission::PageUpdate, $page);
|
|
$this->checkOwnablePermission(Permission::AttachmentUpdate, $attachment);
|
|
|
|
if ($request->hasFile('file')) {
|
|
$uploadedFile = $request->file('file');
|
|
$attachment = $this->attachmentService->saveUpdatedUpload($uploadedFile, $attachment);
|
|
}
|
|
|
|
$this->attachmentService->updateFile($attachment, $requestData);
|
|
|
|
return response()->json($attachment);
|
|
}
|
|
|
|
/**
|
|
* Delete an attachment of the given ID.
|
|
*
|
|
* @throws Exception
|
|
*/
|
|
public function delete(string $id)
|
|
{
|
|
/** @var Attachment $attachment */
|
|
$attachment = Attachment::visible()->findOrFail($id);
|
|
$this->checkOwnablePermission(Permission::AttachmentDelete, $attachment);
|
|
|
|
$this->attachmentService->deleteFile($attachment);
|
|
|
|
return response('', 204);
|
|
}
|
|
|
|
protected function rules(): array
|
|
{
|
|
return [
|
|
'create' => [
|
|
'name' => ['required', 'string', 'min:1', 'max:255'],
|
|
'uploaded_to' => ['required', 'integer', new EntityExistsRule('page')],
|
|
'file' => array_merge(['required_without:link'], $this->attachmentService->getFileValidationRules()),
|
|
'link' => ['required_without:file', 'string', 'min:1', 'max:2000', 'safe_url'],
|
|
],
|
|
'update' => [
|
|
'name' => ['string', 'min:1', 'max:255'],
|
|
'uploaded_to' => ['integer', new EntityExistsRule('page')],
|
|
'file' => $this->attachmentService->getFileValidationRules(),
|
|
'link' => ['string', 'min:1', 'max:2000', 'safe_url'],
|
|
],
|
|
];
|
|
}
|
|
}
|