1 <?php namespace BookStack\Http\Controllers;
3 use BookStack\Exceptions\FileUploadException;
5 use BookStack\Repos\PageRepo;
6 use BookStack\Services\FileService;
7 use Illuminate\Http\Request;
9 use BookStack\Http\Requests;
11 class FileController extends Controller
13 protected $fileService;
18 * FileController constructor.
19 * @param FileService $fileService
21 * @param PageRepo $pageRepo
23 public function __construct(FileService $fileService, File $file, PageRepo $pageRepo)
25 $this->fileService = $fileService;
27 $this->pageRepo = $pageRepo;
32 * Endpoint at which files are uploaded to.
33 * @param Request $request
35 public function upload(Request $request)
37 // TODO - ensure uploads are deleted on page delete.
38 $this->validate($request, [
39 'uploaded_to' => 'required|integer|exists:pages,id'
42 $pageId = $request->get('uploaded_to');
43 $page = $this->pageRepo->getById($pageId);
45 $this->checkPermission('file-create-all');
46 $this->checkOwnablePermission('page-update', $page);
48 $uploadedFile = $request->file('file');
51 $file = $this->fileService->saveNewUpload($uploadedFile, $pageId);
52 } catch (FileUploadException $e) {
53 return response($e->getMessage(), 500);
56 return response()->json($file);
60 * Get the files for a specific page.
64 public function listForPage($pageId)
66 $page = $this->pageRepo->getById($pageId);
67 $this->checkOwnablePermission('page-view', $page);
68 return response()->json($page->files);
72 * Update the file sorting.
74 * @param Request $request
77 public function sortForPage($pageId, Request $request)
79 $this->validate($request, [
80 'files' => 'required|array',
81 'files.*.id' => 'required|integer',
83 $page = $this->pageRepo->getById($pageId);
84 $this->checkOwnablePermission('page-update', $page);
86 $files = $request->get('files');
87 $this->fileService->updateFileOrderWithinPage($files, $pageId);
88 return response()->json(['message' => 'File order updated']);
92 * Get a file from storage.
95 public function get($fileId)
97 $file = $this->file->findOrFail($fileId);
98 $page = $this->pageRepo->getById($file->uploaded_to);
99 $this->checkOwnablePermission('page-view', $page);
101 $fileContents = $this->fileService->getFile($file);
102 return response($fileContents, 200, [
103 'Content-Type' => 'application/octet-stream',
104 'Content-Disposition' => 'attachment; filename="'. $file->name .'"'
109 * Delete a specific file in the system.
113 public function delete($fileId)
115 $file = $this->file->findOrFail($fileId);
116 $this->checkOwnablePermission($file, 'file-delete');
117 $this->fileService->deleteFile($file);
118 return response()->json(['message' => 'File deleted']);