]> BookStack Code Mirror - bookstack/blob - app/Services/FileService.php
689fa0600360107c85a7de815d568aa8a7158165
[bookstack] / app / Services / FileService.php
1 <?php namespace BookStack\Services;
2
3
4 use BookStack\Exceptions\FileUploadException;
5 use BookStack\File;
6 use Exception;
7 use Illuminate\Support\Collection;
8 use Symfony\Component\HttpFoundation\File\UploadedFile;
9
10 class FileService extends UploadService
11 {
12
13     /**
14      * Store a new file upon user upload.
15      * @param UploadedFile $uploadedFile
16      * @param int $page_id
17      * @return File
18      * @throws FileUploadException
19      */
20     public function saveNewUpload(UploadedFile $uploadedFile, $page_id)
21     {
22         $fileName = $uploadedFile->getClientOriginalName();
23         $fileData = file_get_contents($uploadedFile->getRealPath());
24
25         $storage = $this->getStorage();
26         $fileBasePath = 'uploads/files/' . Date('Y-m-M') . '/';
27         $storageBasePath = $this->getStorageBasePath() . $fileBasePath;
28
29         $uploadFileName = $fileName;
30         while ($storage->exists($storageBasePath . $uploadFileName)) {
31             $uploadFileName = str_random(3) . $uploadFileName;
32         }
33
34         $filePath = $fileBasePath . $uploadFileName;
35         $fileStoragePath = $this->getStorageBasePath() . $filePath;
36
37         try {
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.');
41         }
42
43         $largestExistingOrder = File::where('uploaded_to', '=', $page_id)->max('order');
44
45         $file = File::forceCreate([
46             'name' => $fileName,
47             'path' => $filePath,
48             'uploaded_to' => $page_id,
49             'created_by' => user()->id,
50             'updated_by' => user()->id,
51             'order' => $largestExistingOrder + 1
52         ]);
53
54         return $file;
55     }
56
57     /**
58      * Get the file storage base path, amended for storage type.
59      * This allows us to keep a generic path in the database.
60      * @return string
61      */
62     private function getStorageBasePath()
63     {
64         return $this->isLocal() ? 'storage/' : '';
65     }
66
67     /**
68      * Updates the file ordering for a listing of attached files.
69      * @param array $fileList
70      * @param $pageId
71      */
72     public function updateFileOrderWithinPage($fileList, $pageId)
73     {
74         foreach ($fileList as $index => $file) {
75             File::where('uploaded_to', '=', $pageId)->where('id', '=', $file['id'])->update(['order' => $index]);
76         }
77     }
78
79 }