1 <?php namespace BookStack\Services;
4 use BookStack\Exceptions\FileUploadException;
7 use Illuminate\Support\Collection;
8 use Symfony\Component\HttpFoundation\File\UploadedFile;
10 class FileService extends UploadService
14 * Store a new file upon user upload.
15 * @param UploadedFile $uploadedFile
18 * @throws FileUploadException
20 public function saveNewUpload(UploadedFile $uploadedFile, $page_id)
22 $fileName = $uploadedFile->getClientOriginalName();
23 $fileData = file_get_contents($uploadedFile->getRealPath());
25 $storage = $this->getStorage();
26 $fileBasePath = 'uploads/files/' . Date('Y-m-M') . '/';
27 $storageBasePath = $this->getStorageBasePath() . $fileBasePath;
29 $uploadFileName = $fileName;
30 while ($storage->exists($storageBasePath . $uploadFileName)) {
31 $uploadFileName = str_random(3) . $uploadFileName;
34 $filePath = $fileBasePath . $uploadFileName;
35 $fileStoragePath = $this->getStorageBasePath() . $filePath;
38 $storage->put($fileStoragePath, $fileData);
39 } catch (Exception $e) {
40 throw new FileUploadException('File path ' . $fileStoragePath . ' could not be uploaded to. Ensure it is writable to the server.');
43 $largestExistingOrder = File::where('uploaded_to', '=', $page_id)->max('order');
45 $file = File::forceCreate([
48 'uploaded_to' => $page_id,
49 'created_by' => user()->id,
50 'updated_by' => user()->id,
51 'order' => $largestExistingOrder + 1
58 * Get the file storage base path, amended for storage type.
59 * This allows us to keep a generic path in the database.
62 private function getStorageBasePath()
64 return $this->isLocal() ? 'storage/' : '';
68 * Updates the file ordering for a listing of attached files.
69 * @param array $fileList
72 public function updateFileOrderWithinPage($fileList, $pageId)
74 foreach ($fileList as $index => $file) {
75 File::where('uploaded_to', '=', $pageId)->where('id', '=', $file['id'])->update(['order' => $index]);