3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Core;
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;
32 * Manage storage backends
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.
39 // Default tables to look for data
40 const TABLES = ['photo', 'attach'];
42 // Default storage backends
44 const DEFAULT_BACKENDS = [
45 Storage\Filesystem::NAME,
46 Storage\Database::NAME,
49 /** @var string[] List of valid backend classes */
50 private $validBackends;
53 * @var Storage\IStorage[] A local cache for storage instances
55 private $backendInstances = [];
61 /** @var LoggerInterface */
66 /** @var Storage\IWritableStorage */
67 private $currentBackend;
70 * @param Database $dba
71 * @param IConfig $config
72 * @param LoggerInterface $logger
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
78 public function __construct(Database $dba, IConfig $config, LoggerInterface $logger, L10n $l10n)
81 $this->config = $config;
82 $this->logger = $logger;
84 $this->validBackends = $config->get('storage', 'backends', self::DEFAULT_BACKENDS);
86 $currentName = $this->config->get('storage', 'name');
88 // you can only use user backends as a "default" backend, so the second parameter is true
89 $this->currentBackend = $this->getWritableStorageByName($currentName);
93 * Return current storage backend class
95 * @return Storage\IWritableStorage
97 public function getBackend()
99 return $this->currentBackend;
103 * Returns a writable storage backend class by registered name
105 * @param string $name Backend name
107 * @return Storage\IWritableStorage
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
112 public function getWritableStorageByName(string $name): Storage\IWritableStorage
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));
123 * Return storage backend class by registered name
125 * @param string $name Backend name
126 * @param string[]|null $validBackends possible, manual override of the valid backends
128 * @return Storage\IStorage
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
133 public function getByName(string $name, array $validBackends = null): Storage\IStorage
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));
143 // Try the filesystem backend
144 case Storage\Filesystem::getName():
145 $this->backendInstances[$name] = new Storage\Filesystem($this->config, $this->l10n);
147 // try the database backend
148 case Storage\Database::getName():
149 $this->backendInstances[$name] = new Storage\Database($this->dba);
151 // at least, try if there's an addon for the backend
152 case Storage\SystemResource::getName():
153 $this->backendInstances[$name] = new Storage\SystemResource();
155 case Storage\ExternalResource::getName():
156 $this->backendInstances[$name] = new Storage\ExternalResource();
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));
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);
177 return $this->backendInstances[$name];
181 * Checks, if the storage is a valid backend
183 * @param string|null $name The name or class of the backend
184 * @param string[]|null $validBackends Possible, valid backends to check
186 * @return boolean True, if the backend is a valid backend
188 public function isValidBackend(string $name = null, array $validBackends = null): bool
190 $validBackends = $validBackends ?? array_merge($this->validBackends,
192 Storage\SystemResource::getName(),
193 Storage\ExternalResource::getName(),
195 return in_array($name, $validBackends);
199 * Set current storage backend class
201 * @param Storage\IWritableStorage $storage The storage class
203 * @return boolean True, if the set was successful
205 public function setBackend(Storage\IWritableStorage $storage): bool
207 if ($this->config->set('storage', 'name', $storage::getName())) {
208 $this->currentBackend = $storage;
216 * Get registered backends
220 public function listBackends(): array
222 return $this->validBackends;
226 * Register a storage backend class
228 * You have to register the hook "storage_instance" as well to make this class work!
230 * @param string $class Backend class name
232 * @return boolean True, if the registration was successful
234 public function register(string $class): bool
236 if (is_subclass_of($class, Storage\IStorage::class)) {
237 /** @var Storage\IStorage $class */
239 if ($this->isValidBackend($class::getName(), $this->validBackends)) {
243 $backends = $this->validBackends;
244 $backends[] = $class::getName();
246 if ($this->config->set('storage', 'backends', $backends)) {
247 $this->validBackends = $backends;
258 * Unregister a storage backend class
260 * @param string $class Backend class name
262 * @return boolean True, if unregistering was successful
264 * @throws Storage\StorageException
266 public function unregister(string $class): bool
268 if (is_subclass_of($class, Storage\IStorage::class)) {
269 /** @var Storage\IStorage $class */
271 if ($this->currentBackend::getName() == $class::getName()) {
272 throw new Storage\StorageException(sprintf('Cannot unregister %s, because it\'s currently active.', $class::getName()));
275 $key = array_search($class::getName(), $this->validBackends);
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;
296 * Move up to 5000 resources to storage $dest
298 * Copy existing data to destination storage and delete from source.
299 * This method cannot move to legacy in-table `data` field.
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
305 * @return int Number of moved resources
306 * @throws Storage\StorageException
309 public function move(Storage\IWritableStorage $destination, array $tables = self::TABLES, int $limit = 5000): int
311 if (!$this->isValidBackend($destination, $this->validBackends)) {
312 throw new Storage\StorageException(sprintf("Can't move to storage backend '%s'", $destination::getName()));
316 foreach ($tables as $table) {
317 // Get the rows where backend class is not the destination backend class
318 $resources = $this->dba->select(
320 ['id', 'data', 'backend-class', 'backend-ref'],
321 ['`backend-class` IS NULL or `backend-class` != ?', $destination::getName()],
325 while ($resource = $this->dba->fetch($resources)) {
326 $id = $resource['id'];
327 $sourceRef = $resource['backend-ref'];
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]);
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]);
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);
358 $this->dba->close($resources);