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