]> git.mxchange.org Git - friendica.git/blob - src/Model/Storage/Filesystem.php
We now store the causer-id in the items
[friendica.git] / src / Model / Storage / Filesystem.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
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 Friendica\Core\Config\IConfig;
25 use Friendica\Core\L10n;
26 use Friendica\Util\Strings;
27 use Psr\Log\LoggerInterface;
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 extends AbstractStorage
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         /**
53          * Filesystem constructor.
54          *
55          * @param IConfig         $config
56          * @param LoggerInterface $logger
57          * @param L10n            $l10n
58          */
59         public function __construct(IConfig $config, LoggerInterface $logger, L10n $l10n)
60         {
61                 parent::__construct($l10n, $logger);
62
63                 $this->config = $config;
64
65                 $path           = $this->config->get('storage', 'filesystem_path', self::DEFAULT_BASE_FOLDER);
66                 $this->basePath = rtrim($path, '/');
67         }
68
69         /**
70          * Split data ref and return file path
71          *
72          * @param string $reference Data reference
73          *
74          * @return string
75          */
76         private function pathForRef(string $reference)
77         {
78                 $fold1 = substr($reference, 0, 2);
79                 $fold2 = substr($reference, 2, 2);
80                 $file  = substr($reference, 4);
81
82                 return implode('/', [$this->basePath, $fold1, $fold2, $file]);
83         }
84
85
86         /**
87          * Create dirctory tree to store file, with .htaccess and index.html files
88          *
89          * @param string $file Path and filename
90          *
91          * @throws StorageException
92          */
93         private function createFoldersForFile(string $file)
94         {
95                 $path = dirname($file);
96
97                 if (!is_dir($path)) {
98                         if (!mkdir($path, 0770, true)) {
99                                 $this->logger->warning('Failed to create dir.', ['path' => $path]);
100                                 throw new StorageException($this->l10n->t('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)
122         {
123                 $file = $this->pathForRef($reference);
124                 if (!is_file($file)) {
125                         return '';
126                 }
127
128                 return file_get_contents($file);
129         }
130
131         /**
132          * @inheritDoc
133          */
134         public function put(string $data, string $reference = '')
135         {
136                 if ($reference === '') {
137                         $reference = Strings::getRandomHex();
138                 }
139                 $file = $this->pathForRef($reference);
140
141                 $this->createFoldersForFile($file);
142
143                 $result = file_put_contents($file, $data);
144
145                 // just in case the result is REALLY false, not zero or empty or anything else, throw the exception
146                 if ($result === false) {
147                         $this->logger->warning('Failed to write data.', ['file' => $file]);
148                         throw new StorageException($this->l10n->t('Filesystem storage failed to save data to "%s". Check your write permissions', $file));
149                 }
150
151                 chmod($file, 0660);
152                 return $reference;
153         }
154
155         /**
156          * @inheritDoc
157          */
158         public function delete(string $reference)
159         {
160                 $file = $this->pathForRef($reference);
161                 // return true if file doesn't exists. we want to delete it: success with zero work!
162                 if (!is_file($file)) {
163                         return true;
164                 }
165                 return unlink($file);
166         }
167
168         /**
169          * @inheritDoc
170          */
171         public function getOptions()
172         {
173                 return [
174                         'storagepath' => [
175                                 'input',
176                                 $this->l10n->t('Storage base path'),
177                                 $this->basePath,
178                                 $this->l10n->t('Folder where uploaded files are saved. For maximum security, This should be a path outside web server folder tree')
179                         ]
180                 ];
181         }
182
183         /**
184          * @inheritDoc
185          */
186         public function saveOptions(array $data)
187         {
188                 $storagePath = $data['storagepath'] ?? '';
189                 if ($storagePath === '' || !is_dir($storagePath)) {
190                         return [
191                                 'storagepath' => $this->l10n->t('Enter a valid existing folder')
192                         ];
193                 };
194                 $this->config->set('storage', 'filesystem_path', $storagePath);
195                 $this->basePath = $storagePath;
196                 return [];
197         }
198
199         /**
200          * @inheritDoc
201          */
202         public static function getName()
203         {
204                 return self::NAME;
205         }
206 }