3 namespace BookStack\Uploads\Controllers;
5 use BookStack\Entities\Queries\PageQueries;
6 use BookStack\Exceptions\FileUploadException;
7 use BookStack\Http\ApiController;
8 use BookStack\Permissions\Permission;
9 use BookStack\Uploads\Attachment;
10 use BookStack\Uploads\AttachmentService;
12 use Illuminate\Contracts\Filesystem\FileNotFoundException;
13 use Illuminate\Http\Request;
14 use Illuminate\Validation\ValidationException;
16 class AttachmentApiController extends ApiController
18 public function __construct(
19 protected AttachmentService $attachmentService,
20 protected PageQueries $pageQueries,
25 * Get a listing of attachments visible to the user.
26 * The external property indicates whether the attachment is simple a link.
27 * A false value for the external property would indicate a file upload.
29 public function list()
31 return $this->apiListingResponse(Attachment::visible(), [
32 'id', 'name', 'extension', 'uploaded_to', 'external', 'order', 'created_at', 'updated_at', 'created_by', 'updated_by',
37 * Create a new attachment in the system.
38 * An uploaded_to value must be provided containing an ID of the page
39 * that this upload will be related to.
41 * If you're uploading a file the POST data should be provided via
42 * a multipart/form-data type request instead of JSON.
44 * @throws ValidationException
45 * @throws FileUploadException
47 public function create(Request $request)
49 $this->checkPermission(Permission::AttachmentCreateAll);
50 $requestData = $this->validate($request, $this->rules()['create']);
52 $pageId = $request->get('uploaded_to');
53 $page = $this->pageQueries->findVisibleByIdOrFail($pageId);
54 $this->checkOwnablePermission(Permission::PageUpdate, $page);
56 if ($request->hasFile('file')) {
57 $uploadedFile = $request->file('file');
58 $attachment = $this->attachmentService->saveNewUpload($uploadedFile, $page->id);
60 $attachment = $this->attachmentService->saveNewFromLink(
67 $this->attachmentService->updateFile($attachment, $requestData);
69 return response()->json($attachment);
73 * Get the details & content of a single attachment of the given ID.
74 * The attachment link or file content is provided via a 'content' property.
75 * For files the content will be base64 encoded.
77 * @throws FileNotFoundException
79 public function read(string $id)
81 /** @var Attachment $attachment */
82 $attachment = Attachment::visible()
83 ->with(['createdBy', 'updatedBy'])
86 $attachment->setAttribute('links', [
87 'html' => $attachment->htmlLink(),
88 'markdown' => $attachment->markdownLink(),
91 // Simply return a JSON response of the attachment for link-based attachments
92 if ($attachment->external) {
93 $attachment->setAttribute('content', $attachment->path);
95 return response()->json($attachment);
98 // Build and split our core JSON, at point of content.
99 $splitter = 'CONTENT_SPLIT_LOCATION_' . time() . '_' . rand(1, 40000);
100 $attachment->setAttribute('content', $splitter);
101 $json = $attachment->toJson();
102 $jsonParts = explode($splitter, $json);
103 // Get a stream for the file data from storage
104 $stream = $this->attachmentService->streamAttachmentFromStorage($attachment);
106 return response()->stream(function () use ($jsonParts, $stream) {
107 // Output the pre-content JSON data
110 // Stream out our attachment data as base64 content
111 stream_filter_append($stream, 'convert.base64-encode', STREAM_FILTER_READ);
115 // Output our post-content JSON data
117 }, 200, ['Content-Type' => 'application/json']);
121 * Update the details of a single attachment.
122 * As per the create endpoint, if a file is being provided as the attachment content
123 * the request should be formatted as a multipart/form-data request instead of JSON.
125 * @throws ValidationException
126 * @throws FileUploadException
128 public function update(Request $request, string $id)
130 $requestData = $this->validate($request, $this->rules()['update']);
131 /** @var Attachment $attachment */
132 $attachment = Attachment::visible()->findOrFail($id);
134 $page = $attachment->page;
135 if ($requestData['uploaded_to'] ?? false) {
136 $pageId = $request->get('uploaded_to');
137 $page = $this->pageQueries->findVisibleByIdOrFail($pageId);
138 $attachment->uploaded_to = $requestData['uploaded_to'];
141 $this->checkOwnablePermission(Permission::PageView, $page);
142 $this->checkOwnablePermission(Permission::PageUpdate, $page);
143 $this->checkOwnablePermission(Permission::AttachmentUpdate, $attachment);
145 if ($request->hasFile('file')) {
146 $uploadedFile = $request->file('file');
147 $attachment = $this->attachmentService->saveUpdatedUpload($uploadedFile, $attachment);
150 $this->attachmentService->updateFile($attachment, $requestData);
152 return response()->json($attachment);
156 * Delete an attachment of the given ID.
160 public function delete(string $id)
162 /** @var Attachment $attachment */
163 $attachment = Attachment::visible()->findOrFail($id);
164 $this->checkOwnablePermission(Permission::AttachmentDelete, $attachment);
166 $this->attachmentService->deleteFile($attachment);
168 return response('', 204);
171 protected function rules(): array
175 'name' => ['required', 'string', 'min:1', 'max:255'],
176 'uploaded_to' => ['required', 'integer', 'exists:pages,id'],
177 'file' => array_merge(['required_without:link'], $this->attachmentService->getFileValidationRules()),
178 'link' => ['required_without:file', 'string', 'min:1', 'max:2000', 'safe_url'],
181 'name' => ['string', 'min:1', 'max:255'],
182 'uploaded_to' => ['integer', 'exists:pages,id'],
183 'file' => $this->attachmentService->getFileValidationRules(),
184 'link' => ['string', 'min:1', 'max:2000', 'safe_url'],