]> git.mxchange.org Git - friendica.git/blob - src/Core/StorageManager.php
ede8966f41b47b227b5eb2777d1ebf667e1352be
[friendica.git] / src / Core / StorageManager.php
1 <?php
2
3 namespace Friendica\Core;
4
5 use Dice\Dice;
6 use Exception;
7 use Friendica\Core\Config\IConfiguration;
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         /** @var Database */
33         private $dba;
34         /** @var IConfiguration */
35         private $config;
36         /** @var LoggerInterface */
37         private $logger;
38         /** @var Dice */
39         private $dice;
40
41         /** @var Storage\IStorage */
42         private $currentBackend;
43
44         /**
45          * @param Database        $dba
46          * @param IConfiguration  $config
47          * @param LoggerInterface $logger
48          */
49         public function __construct(Database $dba, IConfiguration $config, LoggerInterface $logger, Dice $dice)
50         {
51                 $this->dba      = $dba;
52                 $this->config   = $config;
53                 $this->logger   = $logger;
54                 $this->dice     = $dice;
55                 $this->backends = $config->get('storage', 'backends', self::DEFAULT_BACKENDS);
56
57                 $currentName = $this->config->get('storage', 'name', '');
58
59                 if ($this->isValidBackend($currentName)) {
60                         $this->currentBackend = $this->dice->create($this->backends[$currentName]);
61                 } else {
62                         $this->currentBackend = null;
63                 }
64         }
65
66         /**
67          * @brief Return current storage backend class
68          *
69          * @return Storage\IStorage|null
70          */
71         public function getBackend()
72         {
73                 return $this->currentBackend;
74         }
75
76         /**
77          * @brief Return storage backend class by registered name
78          *
79          * @param string $name Backend name
80          *
81          * @return Storage\IStorage|null null if no backend registered at $name
82          */
83         public function getByName(string $name)
84         {
85                 if (!$this->isValidBackend($name)) {
86                         return null;
87                 }
88
89                 return $this->dice->create($this->backends[$name]);
90         }
91
92         /**
93          * Checks, if the storage is a valid backend
94          *
95          * @param string $name The name or class of the backend
96          *
97          * @return boolean True, if the backend is a valid backend
98          */
99         public function isValidBackend(string $name)
100         {
101                 return array_key_exists($name, $this->backends);
102         }
103
104         /**
105          * @brief Set current storage backend class
106          *
107          * @param string $name Backend class name
108          *
109          * @return boolean True, if the set was successful
110          */
111         public function setBackend(string $name)
112         {
113                 if (!$this->isValidBackend($name)) {
114                         return false;
115                 }
116
117                 if ($this->config->set('storage', 'name', $name)) {
118                         $this->currentBackend = $this->dice->create($this->backends[$name]);
119                         return true;
120                 } else {
121                         return false;
122                 }
123         }
124
125         /**
126          * @brief Get registered backends
127          *
128          * @return array
129          */
130         public function listBackends()
131         {
132                 return $this->backends;
133         }
134
135         /**
136          * @brief Register a storage backend class
137          *
138          * @param string $name  User readable backend name
139          * @param string $class Backend class name
140          *
141          * @return boolean True, if the registration was successful
142          */
143         public function register(string $name, string $class)
144         {
145                 if (!is_subclass_of($class, Storage\IStorage::class)) {
146                         return false;
147                 }
148
149                 $backends        = $this->backends;
150                 $backends[$name] = $class;
151
152                 if ($this->config->set('storage', 'backends', $this->backends)) {
153                         $this->backends = $backends;
154                         return true;
155                 } else {
156                         return false;
157                 }
158         }
159
160         /**
161          * @brief Unregister a storage backend class
162          *
163          * @param string $name User readable backend name
164          *
165          * @return boolean True, if unregistering was successful
166          */
167         public function unregister(string $name)
168         {
169                 unset($this->backends[$name]);
170                 return $this->config->set('storage', 'backends', $this->backends);
171         }
172
173         /**
174          * @brief Move up to 5000 resources to storage $dest
175          *
176          * Copy existing data to destination storage and delete from source.
177          * This method cannot move to legacy in-table `data` field.
178          *
179          * @param Storage\IStorage $destination Destination storage class name
180          * @param array            $tables      Tables to look in for resources. Optional, defaults to ['photo', 'attach']
181          * @param int              $limit       Limit of the process batch size, defaults to 5000
182          *
183          * @return int Number of moved resources
184          * @throws Storage\StorageException
185          * @throws Exception
186          */
187         public function move(Storage\IStorage $destination, array $tables = self::TABLES, int $limit = 5000)
188         {
189                 if ($destination === null) {
190                         throw new Storage\StorageException('Can\'t move to NULL storage backend');
191                 }
192
193                 $moved = 0;
194                 foreach ($tables as $table) {
195                         // Get the rows where backend class is not the destination backend class
196                         $resources = $this->dba->select(
197                                 $table,
198                                 ['id', 'data', 'backend-class', 'backend-ref'],
199                                 ['`backend-class` IS NULL or `backend-class` != ?', $destination],
200                                 ['limit' => $limit]
201                         );
202
203                         while ($resource = $this->dba->fetch($resources)) {
204                                 $id        = $resource['id'];
205                                 $data      = $resource['data'];
206                                 $source    = $this->getByName($resource['backend-class']);
207                                 $sourceRef = $resource['backend-ref'];
208
209                                 if (!empty($source)) {
210                                         $this->logger->info('Get data from old backend.', ['oldBackend' => $source, 'oldReference' => $sourceRef]);
211                                         $data = $source->get($sourceRef);
212                                 }
213
214                                 $this->logger->info('Save data to new backend.', ['newBackend' => $destination]);
215                                 $destinationRef = $destination->put($data);
216                                 $this->logger->info('Saved data.', ['newReference' => $destinationRef]);
217
218                                 if ($destinationRef !== '') {
219                                         $this->logger->info('update row');
220                                         if ($this->dba->update($table, ['backend-class' => $destination, 'backend-ref' => $destinationRef, 'data' => ''], ['id' => $id])) {
221                                                 if (!empty($source)) {
222                                                         $this->logger->info('Delete data from old backend.', ['oldBackend' => $source, 'oldReference' => $sourceRef]);
223                                                         $source->delete($sourceRef);
224                                                 }
225                                                 $moved++;
226                                         }
227                                 }
228                         }
229
230                         $this->dba->close($resources);
231                 }
232
233                 return $moved;
234         }
235 }