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