3 * @copyright Copyright (C) 2010-2022, 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\Storage\Repository;
25 use Friendica\Core\Config\Capability\IManageConfigValues;
26 use Friendica\Core\Hook;
27 use Friendica\Core\L10n;
28 use Friendica\Core\Storage\Exception\InvalidClassStorageException;
29 use Friendica\Core\Storage\Exception\ReferenceStorageException;
30 use Friendica\Core\Storage\Exception\StorageException;
31 use Friendica\Core\Storage\Capability\ICanReadFromStorage;
32 use Friendica\Core\Storage\Capability\ICanConfigureStorage;
33 use Friendica\Core\Storage\Capability\ICanWriteToStorage;
34 use Friendica\Database\Database;
35 use Friendica\Core\Storage\Type;
36 use Friendica\Network\HTTPException\InternalServerErrorException;
37 use Psr\Log\LoggerInterface;
40 * Manage storage backends
42 * Core code uses this class to get and set current storage backend class.
43 * Addons use this class to register and unregister additional backends.
47 // Default tables to look for data
48 const TABLES = ['photo', 'attach'];
50 // Default storage backends
52 const DEFAULT_BACKENDS = [
53 Type\Filesystem::NAME,
57 /** @var string[] List of valid backend classes */
58 private $validBackends;
61 * @var ICanReadFromStorage[] A local cache for storage instances
63 private $backendInstances = [];
67 /** @var IManageConfigValues */
69 /** @var LoggerInterface */
74 /** @var ICanWriteToStorage */
75 private $currentBackend;
78 * @param Database $dba
79 * @param IManageConfigValues $config
80 * @param LoggerInterface $logger
83 * @throws InvalidClassStorageException in case the active backend class is invalid
84 * @throws StorageException in case of unexpected errors during the active backend class loading
86 public function __construct(Database $dba, IManageConfigValues $config, LoggerInterface $logger, L10n $l10n)
89 $this->config = $config;
90 $this->logger = $logger;
92 $this->validBackends = $config->get('storage', 'backends', self::DEFAULT_BACKENDS);
94 $currentName = $this->config->get('storage', 'name');
96 // you can only use user backends as a "default" backend, so the second parameter is true
97 $this->currentBackend = $this->getWritableStorageByName($currentName);
101 * Return current storage backend class
103 * @return ICanWriteToStorage
105 public function getBackend(): ICanWriteToStorage
107 return $this->currentBackend;
111 * Returns a writable storage backend class by registered name
113 * @param string $name Backend name
115 * @return ICanWriteToStorage
117 * @throws InvalidClassStorageException in case there's no backend class for the name
118 * @throws StorageException in case of an unexpected failure during the hook call
120 public function getWritableStorageByName(string $name): ICanWriteToStorage
122 $storage = $this->getByName($name, $this->validBackends);
123 if (!$storage instanceof ICanWriteToStorage) {
124 throw new InvalidClassStorageException(sprintf('Backend %s is not writable', $name));
131 * Return storage backend configuration by registered name
133 * @param string $name Backend name
135 * @return ICanConfigureStorage|false
137 * @throws InvalidClassStorageException in case there's no backend class for the name
138 * @throws StorageException in case of an unexpected failure during the hook call
140 public function getConfigurationByName(string $name)
143 // Try the filesystem backend
144 case Type\Filesystem::getName():
145 return new Type\FilesystemConfig($this->config, $this->l10n);
146 // try the database backend
147 case Type\Database::getName():
152 'storage_config' => null,
155 Hook::callAll('storage_config', $data);
156 if (!($data['storage_config'] ?? null) instanceof ICanConfigureStorage) {
157 throw new InvalidClassStorageException(sprintf('Configuration for backend %s was not found', $name));
160 return $data['storage_config'];
161 } catch (InternalServerErrorException $exception) {
162 throw new StorageException(sprintf('Failed calling hook::storage_config for backend %s', $name), $exception);
168 * Return storage backend class by registered name
170 * @param string $name Backend name
171 * @param string[]|null $validBackends possible, manual override of the valid backends
173 * @return ICanReadFromStorage
175 * @throws InvalidClassStorageException in case there's no backend class for the name
176 * @throws StorageException in case of an unexpected failure during the hook call
178 public function getByName(string $name, array $validBackends = null): ICanReadFromStorage
180 // If there's no cached instance create a new instance
181 if (!isset($this->backendInstances[$name])) {
182 // If the current name isn't a valid backend (or the SystemResource instance) create it
183 if (!$this->isValidBackend($name, $validBackends)) {
184 throw new InvalidClassStorageException(sprintf('Backend %s is not valid', $name));
188 // Try the filesystem backend
189 case Type\Filesystem::getName():
190 $storageConfig = new Type\FilesystemConfig($this->config, $this->l10n);
191 $this->backendInstances[$name] = new Type\Filesystem($storageConfig->getStoragePath());
193 // try the database backend
194 case Type\Database::getName():
195 $this->backendInstances[$name] = new Type\Database($this->dba);
197 // at least, try if there's an addon for the backend
198 case Type\SystemResource::getName():
199 $this->backendInstances[$name] = new Type\SystemResource();
201 case Type\ExternalResource::getName():
202 $this->backendInstances[$name] = new Type\ExternalResource();
210 Hook::callAll('storage_instance', $data);
211 if (!($data['storage'] ?? null) instanceof ICanReadFromStorage) {
212 throw new InvalidClassStorageException(sprintf('Backend %s was not found', $name));
215 $this->backendInstances[$data['name'] ?? $name] = $data['storage'];
216 } catch (InternalServerErrorException $exception) {
217 throw new StorageException(sprintf('Failed calling hook::storage_instance for backend %s', $name), $exception);
223 return $this->backendInstances[$name];
227 * Checks, if the storage is a valid backend
229 * @param string|null $name The name or class of the backend
230 * @param string[]|null $validBackends Possible, valid backends to check
232 * @return boolean True, if the backend is a valid backend
234 public function isValidBackend(string $name = null, array $validBackends = null): bool
236 $validBackends = $validBackends ?? array_merge($this->validBackends,
238 Type\SystemResource::getName(),
239 Type\ExternalResource::getName(),
241 return in_array($name, $validBackends);
245 * Set current storage backend class
247 * @param ICanWriteToStorage $storage The storage class
249 * @return boolean True, if the set was successful
251 public function setBackend(ICanWriteToStorage $storage): bool
253 if ($this->config->set('storage', 'name', $storage::getName())) {
254 $this->currentBackend = $storage;
262 * Get registered backends
266 public function listBackends(): array
268 return $this->validBackends;
272 * Register a storage backend class
274 * You have to register the hook "storage_instance" as well to make this class work!
276 * @param string $class Backend class name
278 * @return boolean True, if the registration was successful
280 public function register(string $class): bool
282 if (is_subclass_of($class, ICanReadFromStorage::class)) {
283 /** @var ICanReadFromStorage $class */
284 if ($this->isValidBackend($class::getName(), $this->validBackends)) {
288 $backends = $this->validBackends;
289 $backends[] = $class::getName();
291 if ($this->config->set('storage', 'backends', $backends)) {
292 $this->validBackends = $backends;
303 * Unregister a storage backend class
305 * @param string $class Backend class name
307 * @return boolean True, if unregistering was successful
309 * @throws StorageException
311 public function unregister(string $class): bool
313 if (is_subclass_of($class, ICanReadFromStorage::class)) {
314 /** @var ICanReadFromStorage $class */
315 if ($this->currentBackend::getName() == $class::getName()) {
316 throw new StorageException(sprintf('Cannot unregister %s, because it\'s currently active.', $class::getName()));
319 $key = array_search($class::getName(), $this->validBackends);
321 if ($key !== false) {
322 $backends = $this->validBackends;
323 unset($backends[$key]);
324 $backends = array_values($backends);
325 if ($this->config->set('storage', 'backends', $backends)) {
326 $this->validBackends = $backends;
340 * Move up to 5000 resources to storage $dest
342 * Copy existing data to destination storage and delete from source.
343 * This method cannot move to legacy in-table `data` field.
345 * @param ICanWriteToStorage $destination Destination storage class name
346 * @param array $tables Tables to look in for resources. Optional, defaults to ['photo', 'attach']
347 * @param int $limit Limit of the process batch size, defaults to 5000
349 * @return int Number of moved resources
350 * @throws StorageException
353 public function move(ICanWriteToStorage $destination, array $tables = self::TABLES, int $limit = 5000): int
355 if (!$this->isValidBackend($destination, $this->validBackends)) {
356 throw new StorageException(sprintf("Can't move to storage backend '%s'", $destination::getName()));
360 foreach ($tables as $table) {
361 // Get the rows where backend class is not the destination backend class
362 $resources = $this->dba->select(
364 ['id', 'data', 'backend-class', 'backend-ref'],
365 ['`backend-class` IS NULL or `backend-class` != ?', $destination::getName()],
369 while ($resource = $this->dba->fetch($resources)) {
370 $id = $resource['id'];
371 $sourceRef = $resource['backend-ref'];
375 $source = $this->getWritableStorageByName($resource['backend-class'] ?? '');
376 $this->logger->info('Get data from old backend.', ['oldBackend' => $source, 'oldReference' => $sourceRef]);
377 $data = $source->get($sourceRef);
378 } catch (InvalidClassStorageException $exception) {
379 $this->logger->info('Get data from DB resource field.', ['oldReference' => $sourceRef]);
380 $data = $resource['data'];
381 } catch (ReferenceStorageException $exception) {
382 $this->logger->info('Invalid source reference.', ['oldBackend' => $source, 'oldReference' => $sourceRef]);
386 $this->logger->info('Save data to new backend.', ['newBackend' => $destination::getName()]);
387 $destinationRef = $destination->put($data);
388 $this->logger->info('Saved data.', ['newReference' => $destinationRef]);
390 if ($destinationRef !== '') {
391 $this->logger->info('update row');
392 if ($this->dba->update($table, ['backend-class' => $destination::getName(), 'backend-ref' => $destinationRef, 'data' => ''], ['id' => $id])) {
393 if (!empty($source)) {
394 $this->logger->info('Deleted data from old backend.', ['oldBackend' => $source, 'oldReference' => $sourceRef]);
395 $source->delete($sourceRef);
402 $this->dba->close($resources);