]> git.mxchange.org Git - friendica.git/blob - src/Model/Storage/Filesystem.php
Update src/Model/Storage/Filesystem.php
[friendica.git] / src / Model / Storage / Filesystem.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Model\Storage;
23
24 use Exception;
25 use Friendica\Core\Config\IConfig;
26 use Friendica\Core\L10n;
27 use Friendica\Util\Strings;
28
29 /**
30  * Filesystem based storage backend
31  *
32  * This class manage data on filesystem.
33  * Base folder for storage is set in storage.filesystem_path.
34  * Best would be for storage folder to be outside webserver folder, we are using a
35  * folder relative to code tree root as default to ease things for users in shared hostings.
36  * Each new resource gets a value as reference and is saved in a
37  * folder tree stucture created from that value.
38  */
39 class Filesystem implements IWritableStorage
40 {
41         const NAME = 'Filesystem';
42
43         // Default base folder
44         const DEFAULT_BASE_FOLDER = 'storage';
45
46         /** @var IConfig */
47         private $config;
48
49         /** @var string */
50         private $basePath;
51
52         /** @var L10n */
53         private $l10n;
54
55         /**
56          * Filesystem constructor.
57          *
58          * @param IConfig         $config
59          * @param L10n            $l10n
60          */
61         public function __construct(IConfig $config, L10n $l10n)
62         {
63                 $this->config = $config;
64                 $this->l10n   = $l10n;
65
66                 $path           = $this->config->get('storage', 'filesystem_path', self::DEFAULT_BASE_FOLDER);
67                 $this->basePath = rtrim($path, '/');
68         }
69
70         /**
71          * Split data ref and return file path
72          *
73          * @param string $reference Data reference
74          *
75          * @return string
76          */
77         private function pathForRef(string $reference): string
78         {
79                 $fold1 = substr($reference, 0, 2);
80                 $fold2 = substr($reference, 2, 2);
81                 $file  = substr($reference, 4);
82
83                 return implode('/', [$this->basePath, $fold1, $fold2, $file]);
84         }
85
86
87         /**
88          * Create directory tree to store file, with .htaccess and index.html files
89          *
90          * @param string $file Path and filename
91          *
92          * @throws StorageException
93          */
94         private function createFoldersForFile(string $file)
95         {
96                 $path = dirname($file);
97
98                 if (!is_dir($path)) {
99                         if (!mkdir($path, 0770, true)) {
100                                 throw new StorageException(sprintf('Filesystem storage failed to create "%s". Check you write permissions.', $path));
101                         }
102                 }
103
104                 while ($path !== $this->basePath) {
105                         if (!is_file($path . '/index.html')) {
106                                 file_put_contents($path . '/index.html', '');
107                         }
108                         chmod($path . '/index.html', 0660);
109                         chmod($path, 0770);
110                         $path = dirname($path);
111                 }
112                 if (!is_file($path . '/index.html')) {
113                         file_put_contents($path . '/index.html', '');
114                         chmod($path . '/index.html', 0660);
115                 }
116         }
117
118         /**
119          * @inheritDoc
120          */
121         public function get(string $reference): string
122         {
123                 $file = $this->pathForRef($reference);
124                 if (!is_file($file)) {
125                         throw new ReferenceStorageException(sprintf('Filesystem storage failed to get the file %s, The file is invalid', $reference));
126                 }
127
128                 $result = file_get_contents($file);
129
130                 if ($result === false) {
131                         throw new StorageException(sprintf('Filesystem storage failed to get data to "%s". Check your write permissions', $file));
132                 }
133
134                 return $result;
135         }
136
137         /**
138          * @inheritDoc
139          */
140         public function put(string $data, string $reference = ''): string
141         {
142                 if ($reference === '') {
143                         try {
144                                 $reference = Strings::getRandomHex();
145                         } catch (Exception $exception) {
146                                 throw new StorageException('Filesystem storage failed to generate a random hex', $exception->getCode(), $exception);
147                         }
148                 }
149                 $file = $this->pathForRef($reference);
150
151                 $this->createFoldersForFile($file);
152
153                 $result = file_put_contents($file, $data);
154
155                 // just in case the result is REALLY false, not zero or empty or anything else, throw the exception
156                 if ($result === false) {
157                         throw new StorageException(sprintf('Filesystem storage failed to save data to "%s". Check your write permissions', $file));
158                 }
159
160                 chmod($file, 0660);
161                 return $reference;
162         }
163
164         /**
165          * @inheritDoc
166          */
167         public function delete(string $reference)
168         {
169                 $file = $this->pathForRef($reference);
170                 if (!is_file($file)) {
171                         throw new ReferenceStorageException(sprintf('File with reference "%s" doesn\'t exist', $reference));
172                 }
173
174                 if (!unlink($file)) {
175                         throw new StorageException(sprintf('Cannot delete with file with reference "%s"', $reference));
176                 }
177         }
178
179         /**
180          * @inheritDoc
181          */
182         public function getOptions(): array
183         {
184                 return [
185                         'storagepath' => [
186                                 'input',
187                                 $this->l10n->t('Storage base path'),
188                                 $this->basePath,
189                                 $this->l10n->t('Folder where uploaded files are saved. For maximum security, This should be a path outside web server folder tree')
190                         ]
191                 ];
192         }
193
194         /**
195          * @inheritDoc
196          */
197         public function saveOptions(array $data): array
198         {
199                 $storagePath = $data['storagepath'] ?? '';
200                 if ($storagePath === '' || !is_dir($storagePath)) {
201                         return [
202                                 'storagepath' => $this->l10n->t('Enter a valid existing folder')
203                         ];
204                 };
205                 $this->config->set('storage', 'filesystem_path', $storagePath);
206                 $this->basePath = $storagePath;
207                 return [];
208         }
209
210         /**
211          * @inheritDoc
212          */
213         public static function getName(): string
214         {
215                 return self::NAME;
216         }
217
218         public function __toString()
219         {
220                 return self::getName();
221         }
222 }