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