]> git.mxchange.org Git - friendica.git/blob - src/Core/StorageManager.php
64e53c10b9f1f62883fa28c23919809774c8947e
[friendica.git] / src / Core / StorageManager.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\Core;
23
24 use Exception;
25 use Friendica\Core\Config\IConfig;
26 use Friendica\Database\Database;
27 use Friendica\Model\Storage;
28 use Friendica\Network\IHTTPRequest;
29 use Psr\Log\LoggerInterface;
30
31
32 /**
33  * Manage storage backends
34  *
35  * Core code uses this class to get and set current storage backend class.
36  * Addons use this class to register and unregister additional backends.
37  */
38 class StorageManager
39 {
40         // Default tables to look for data
41         const TABLES = ['photo', 'attach'];
42
43         // Default storage backends
44         const DEFAULT_BACKENDS = [
45                 Storage\Filesystem::NAME => Storage\Filesystem::class,
46                 Storage\Database::NAME   => Storage\Database::class,
47         ];
48
49         private $backends = [];
50
51         /**
52          * @var Storage\IStorage[] A local cache for storage instances
53          */
54         private $backendInstances = [];
55
56         /** @var Database */
57         private $dba;
58         /** @var IConfig */
59         private $config;
60         /** @var LoggerInterface */
61         private $logger;
62         /** @var L10n */
63         private $l10n;
64         /** @var IHTTPRequest */
65         private $httpRequest;
66
67         /** @var Storage\IStorage */
68         private $currentBackend;
69
70         /**
71          * @param Database        $dba
72          * @param IConfig         $config
73          * @param LoggerInterface $logger
74          * @param L10n            $l10n
75          */
76         public function __construct(Database $dba, IConfig $config, LoggerInterface $logger, L10n $l10n, IHTTPRequest $httpRequest)
77         {
78                 $this->dba         = $dba;
79                 $this->config      = $config;
80                 $this->logger      = $logger;
81                 $this->l10n        = $l10n;
82                 $this->httpRequest = $httpRequest;
83                 $this->backends = $config->get('storage', 'backends', self::DEFAULT_BACKENDS);
84
85                 $currentName = $this->config->get('storage', 'name', '');
86
87                 // you can only use user backends as a "default" backend, so the second parameter is true
88                 $this->currentBackend = $this->getByName($currentName, true);
89         }
90
91         /**
92          * Return current storage backend class
93          *
94          * @return Storage\IStorage|null
95          */
96         public function getBackend()
97         {
98                 return $this->currentBackend;
99         }
100
101         /**
102          * Return storage backend class by registered name
103          *
104          * @param string|null $name            Backend name
105          * @param boolean     $onlyUserBackend True, if just user specific instances should be returrned (e.g. not SystemResource)
106          *
107          * @return Storage\IStorage|null null if no backend registered at $name
108          *
109          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
110          */
111         public function getByName(string $name = null, $onlyUserBackend = false)
112         {
113                 // @todo 2020.09 Remove this call after 2 releases
114                 $name = $this->checkLegacyBackend($name);
115
116                 // If there's no cached instance create a new instance
117                 if (!isset($this->backendInstances[$name])) {
118                         // If the current name isn't a valid backend (or the SystemResource instance) create it
119                         if ($this->isValidBackend($name, $onlyUserBackend)) {
120                                 switch ($name) {
121                                         // Try the filesystem backend
122                                         case Storage\Filesystem::getName():
123                                                 $this->backendInstances[$name] = new Storage\Filesystem($this->config, $this->logger, $this->l10n);
124                                                 break;
125                                         // try the database backend
126                                         case Storage\Database::getName():
127                                                 $this->backendInstances[$name] = new Storage\Database($this->dba, $this->logger, $this->l10n);
128                                                 break;
129                                         // at least, try if there's an addon for the backend
130                                         case Storage\SystemResource::getName():
131                                                 $this->backendInstances[$name] = new Storage\SystemResource();
132                                                 break;
133                                         case Storage\ExternalResource::getName():
134                                                 $this->backendInstances[$name] = new Storage\ExternalResource($this->httpRequest);
135                                                 break;
136                                         default:
137                                                 $data = [
138                                                         'name'    => $name,
139                                                         'storage' => null,
140                                                 ];
141                                                 Hook::callAll('storage_instance', $data);
142                                                 if (($data['storage'] ?? null) instanceof Storage\IStorage) {
143                                                         $this->backendInstances[$data['name'] ?? $name] = $data['storage'];
144                                                 } else {
145                                                         return null;
146                                                 }
147                                                 break;
148                                 }
149                         } else {
150                                 return null;
151                         }
152                 }
153
154                 return $this->backendInstances[$name];
155         }
156
157         /**
158          * Checks, if the storage is a valid backend
159          *
160          * @param string|null $name            The name or class of the backend
161          * @param boolean     $onlyUserBackend True, if just user backend should get returned (e.g. not SystemResource)
162          *
163          * @return boolean True, if the backend is a valid backend
164          */
165         public function isValidBackend(string $name = null, bool $onlyUserBackend = false)
166         {
167                 return array_key_exists($name, $this->backends) ||
168                        (!$onlyUserBackend && in_array($name, [Storage\SystemResource::getName(), Storage\ExternalResource::getName()]));
169         }
170
171         /**
172          * Check for legacy backend storage class names (= full model class name)
173          *
174          * @todo 2020.09 Remove this function after 2 releases, because there shouldn't be any legacy backend classes left
175          *
176          * @param string|null $name a potential, legacy storage name ("Friendica\Model\Storage\...")
177          *
178          * @return string|null The current storage name
179          */
180         private function checkLegacyBackend(string $name = null)
181         {
182                 if (stristr($name, 'Friendica\Model\Storage\\')) {
183                         $this->logger->notice('Using deprecated storage class value', ['name' => $name]);
184                         return substr($name, 24);
185                 }
186
187                 return $name;
188         }
189
190         /**
191          * Set current storage backend class
192          *
193          * @param string $name Backend class name
194          *
195          * @return boolean True, if the set was successful
196          */
197         public function setBackend(string $name = null)
198         {
199                 if (!$this->isValidBackend($name, false)) {
200                         return false;
201                 }
202
203                 if ($this->config->set('storage', 'name', $name)) {
204                         $this->currentBackend = $this->getByName($name, false);
205                         return true;
206                 } else {
207                         return false;
208                 }
209         }
210
211         /**
212          * Get registered backends
213          *
214          * @return array
215          */
216         public function listBackends()
217         {
218                 return $this->backends;
219         }
220
221         /**
222          * Register a storage backend class
223          *
224          * You have to register the hook "storage_instance" as well to make this class work!
225          *
226          * @param string $class Backend class name
227          *
228          * @return boolean True, if the registration was successful
229          */
230         public function register(string $class)
231         {
232                 if (is_subclass_of($class, Storage\IStorage::class)) {
233                         /** @var Storage\IStorage $class */
234
235                         $backends                    = $this->backends;
236                         $backends[$class::getName()] = $class;
237
238                         if ($this->config->set('storage', 'backends', $backends)) {
239                                 $this->backends = $backends;
240                                 return true;
241                         } else {
242                                 return false;
243                         }
244                 } else {
245                         return false;
246                 }
247         }
248
249         /**
250          * Unregister a storage backend class
251          *
252          * @param string $class Backend class name
253          *
254          * @return boolean True, if unregistering was successful
255          */
256         public function unregister(string $class)
257         {
258                 if (is_subclass_of($class, Storage\IStorage::class)) {
259                         /** @var Storage\IStorage $class */
260
261                         unset($this->backends[$class::getName()]);
262
263                         if ($this->currentBackend instanceof $class) {
264                                 $this->config->set('storage', 'name', null);
265                                 $this->currentBackend = null;
266                         }
267
268                         return $this->config->set('storage', 'backends', $this->backends);
269                 } else {
270                         return false;
271                 }
272         }
273
274         /**
275          * Move up to 5000 resources to storage $dest
276          *
277          * Copy existing data to destination storage and delete from source.
278          * This method cannot move to legacy in-table `data` field.
279          *
280          * @param Storage\IStorage $destination Destination storage class name
281          * @param array            $tables      Tables to look in for resources. Optional, defaults to ['photo', 'attach']
282          * @param int              $limit       Limit of the process batch size, defaults to 5000
283          *
284          * @return int Number of moved resources
285          * @throws Storage\StorageException
286          * @throws Exception
287          */
288         public function move(Storage\IStorage $destination, array $tables = self::TABLES, int $limit = 5000)
289         {
290                 if (!$this->isValidBackend($destination, true)) {
291                         throw new Storage\StorageException(sprintf("Can't move to storage backend '%s'", $destination::getName()));
292                 }
293
294                 $moved = 0;
295                 foreach ($tables as $table) {
296                         // Get the rows where backend class is not the destination backend class
297                         $resources = $this->dba->select(
298                                 $table,
299                                 ['id', 'data', 'backend-class', 'backend-ref'],
300                                 ['`backend-class` IS NULL or `backend-class` != ?', $destination::getName()],
301                                 ['limit' => $limit]
302                         );
303
304                         while ($resource = $this->dba->fetch($resources)) {
305                                 $id        = $resource['id'];
306                                 $data      = $resource['data'];
307                                 $source    = $this->getByName($resource['backend-class']);
308                                 $sourceRef = $resource['backend-ref'];
309
310                                 if (!empty($source)) {
311                                         $this->logger->info('Get data from old backend.', ['oldBackend' => $source, 'oldReference' => $sourceRef]);
312                                         $data = $source->get($sourceRef);
313                                 }
314
315                                 $this->logger->info('Save data to new backend.', ['newBackend' => $destination::getName()]);
316                                 $destinationRef = $destination->put($data);
317                                 $this->logger->info('Saved data.', ['newReference' => $destinationRef]);
318
319                                 if ($destinationRef !== '') {
320                                         $this->logger->info('update row');
321                                         if ($this->dba->update($table, ['backend-class' => $destination::getName(), 'backend-ref' => $destinationRef, 'data' => ''], ['id' => $id])) {
322                                                 if (!empty($source)) {
323                                                         $this->logger->info('Delete data from old backend.', ['oldBackend' => $source, 'oldReference' => $sourceRef]);
324                                                         $source->delete($sourceRef);
325                                                 }
326                                                 $moved++;
327                                         }
328                                 }
329                         }
330
331                         $this->dba->close($resources);
332                 }
333
334                 return $moved;
335         }
336 }