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;
33 * Manage storage backends
35 * Core code uses this class to get and set current storage backend class.
36 * Addons use this class to register and unregister additional backends.
40 // Default tables to look for data
41 const TABLES = ['photo', 'attach'];
43 // Default storage backends
44 const DEFAULT_BACKENDS = [
45 Storage\Filesystem::NAME => Storage\Filesystem::class,
46 Storage\Database::NAME => Storage\Database::class,
49 private $backends = [];
52 * @var Storage\IStorage[] A local cache for storage instances
54 private $backendInstances = [];
60 /** @var LoggerInterface */
65 /** @var Storage\IStorage */
66 private $currentBackend;
69 * @param Database $dba
70 * @param IConfig $config
71 * @param LoggerInterface $logger
74 public function __construct(Database $dba, IConfig $config, LoggerInterface $logger, L10n $l10n)
77 $this->config = $config;
78 $this->logger = $logger;
80 $this->backends = $config->get('storage', 'backends', self::DEFAULT_BACKENDS);
82 $currentName = $this->config->get('storage', 'name', '');
84 // you can only use user backends as a "default" backend, so the second parameter is true
85 $this->currentBackend = $this->getWritableStorageByName($currentName);
89 * Return current storage backend class
91 * @return Storage\IWritableStorage|null
93 public function getBackend()
95 return $this->currentBackend;
99 * Returns a writable storage backend class by registered name
101 * @param string $name Backend name
103 * @return Storage\IWritableStorage
105 * @throws Storage\ReferenceStorageException in case there's no backend class for the name
106 * @throws Storage\StorageException in case of an unexpected failure during the hook call
108 public function getWritableStorageByName(string $name = null)
110 // @todo 2020.09 Remove this call after 2 releases
111 $name = $this->checkLegacyBackend($name);
113 // If there's no cached instance create a new instance
114 if (!isset($this->backendInstances[$name])) {
115 // If the current name isn't a valid backend (or the SystemResource instance) create it
116 if ($this->isValidBackend($name, true)) {
118 // Try the filesystem backend
119 case Storage\Filesystem::getName():
120 $this->backendInstances[$name] = new Storage\Filesystem($this->config, $this->l10n);
122 // try the database backend
123 case Storage\Database::getName():
124 $this->backendInstances[$name] = new Storage\Database($this->dba);
132 Hook::callAll('storage_instance', $data);
133 if (($data['storage'] ?? null) instanceof Storage\IWritableStorage) {
134 $this->backendInstances[$data['name'] ?? $name] = $data['storage'];
136 throw new Storage\ReferenceStorageException(sprintf('Backend %s was not found', $name));
138 } catch (InternalServerErrorException $exception) {
139 throw new Storage\StorageException(sprintf('Failed calling hook::storage_instance for backend %s', $name), $exception);
144 throw new Storage\ReferenceStorageException(sprintf('Backend %s is not valid', $name));
148 return $this->backendInstances[$name];
152 * Return storage backend class by registered name
154 * @param string $name Backend name
156 * @return Storage\IStorage
158 * @throws Storage\ReferenceStorageException in case there's no backend class for the name
159 * @throws Storage\StorageException in case of an unexpected failure during the hook call
161 public function getByName(string $name)
163 // @todo 2020.09 Remove this call after 2 releases
164 $name = $this->checkLegacyBackend($name);
166 // If there's no cached instance create a new instance
167 if (!isset($this->backendInstances[$name])) {
168 // If the current name isn't a valid backend (or the SystemResource instance) create it
169 if ($this->isValidBackend($name, false)) {
171 // Try the filesystem backend
172 case Storage\Filesystem::getName():
173 $this->backendInstances[$name] = new Storage\Filesystem($this->config, $this->l10n);
175 // try the database backend
176 case Storage\Database::getName():
177 $this->backendInstances[$name] = new Storage\Database($this->dba);
179 // at least, try if there's an addon for the backend
180 case Storage\SystemResource::getName():
181 $this->backendInstances[$name] = new Storage\SystemResource();
183 case Storage\ExternalResource::getName():
184 $this->backendInstances[$name] = new Storage\ExternalResource();
192 Hook::callAll('storage_instance', $data);
193 if (($data['storage'] ?? null) instanceof Storage\IStorage) {
194 $this->backendInstances[$data['name'] ?? $name] = $data['storage'];
196 throw new Storage\ReferenceStorageException(sprintf('Backend %s was not found', $name));
198 } catch (InternalServerErrorException $exception) {
199 throw new Storage\StorageException(sprintf('Failed calling hook::storage_instance for backend %s', $name), $exception);
204 throw new Storage\ReferenceStorageException(sprintf('Backend %s is not valid', $name));
208 return $this->backendInstances[$name];
212 * Checks, if the storage is a valid backend
214 * @param string|null $name The name or class of the backend
215 * @param boolean $onlyUserBackend True, if just user backend should get returned (e.g. not SystemResource)
217 * @return boolean True, if the backend is a valid backend
219 public function isValidBackend(string $name = null, bool $onlyUserBackend = false)
221 return array_key_exists($name, $this->backends) ||
222 (!$onlyUserBackend && in_array($name, [Storage\SystemResource::getName(), Storage\ExternalResource::getName()]));
226 * Check for legacy backend storage class names (= full model class name)
228 * @todo 2020.09 Remove this function after 2 releases, because there shouldn't be any legacy backend classes left
230 * @param string|null $name a potential, legacy storage name ("Friendica\Model\Storage\...")
232 * @return string|null The current storage name
234 private function checkLegacyBackend(string $name = null)
236 if (stristr($name, 'Friendica\Model\Storage\\')) {
237 $this->logger->notice('Using deprecated storage class value', ['name' => $name]);
238 return substr($name, 24);
245 * Set current storage backend class
247 * @param Storage\IWritableStorage $storage The storage class
249 * @return boolean True, if the set was successful
251 public function setBackend(Storage\IWritableStorage $storage)
253 if ($this->config->set('storage', 'name', $storage::getName())) {
254 $this->currentBackend = $storage;
262 * Get registered backends
266 public function listBackends()
268 return $this->backends;
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)
282 if (is_subclass_of($class, Storage\IStorage::class)) {
283 /** @var Storage\IStorage $class */
285 $backends = $this->backends;
286 $backends[$class::getName()] = $class;
288 if ($this->config->set('storage', 'backends', $backends)) {
289 $this->backends = $backends;
300 * Unregister a storage backend class
302 * @param string $class Backend class name
304 * @return boolean True, if unregistering was successful
306 public function unregister(string $class)
308 if (is_subclass_of($class, Storage\IStorage::class)) {
309 /** @var Storage\IStorage $class */
311 unset($this->backends[$class::getName()]);
313 if ($this->currentBackend instanceof $class) {
314 $this->config->set('storage', 'name', null);
315 $this->currentBackend = null;
318 return $this->config->set('storage', 'backends', $this->backends);
325 * Move up to 5000 resources to storage $dest
327 * Copy existing data to destination storage and delete from source.
328 * This method cannot move to legacy in-table `data` field.
330 * @param Storage\IWritableStorage $destination Destination storage class name
331 * @param array $tables Tables to look in for resources. Optional, defaults to ['photo', 'attach']
332 * @param int $limit Limit of the process batch size, defaults to 5000
334 * @return int Number of moved resources
335 * @throws Storage\StorageException
338 public function move(Storage\IWritableStorage $destination, array $tables = self::TABLES, int $limit = 5000)
340 if (!$this->isValidBackend($destination, true)) {
341 throw new Storage\StorageException(sprintf("Can't move to storage backend '%s'", $destination::getName()));
345 foreach ($tables as $table) {
346 // Get the rows where backend class is not the destination backend class
347 $resources = $this->dba->select(
349 ['id', 'data', 'backend-class', 'backend-ref'],
350 ['`backend-class` IS NULL or `backend-class` != ?', $destination::getName()],
354 while ($resource = $this->dba->fetch($resources)) {
355 $id = $resource['id'];
356 $data = $resource['data'];
357 $source = $this->getWritableStorageByName($resource['backend-class']);
358 $sourceRef = $resource['backend-ref'];
360 if (!empty($source)) {
361 $this->logger->info('Get data from old backend.', ['oldBackend' => $source, 'oldReference' => $sourceRef]);
362 $data = $source->get($sourceRef);
365 $this->logger->info('Save data to new backend.', ['newBackend' => $destination::getName()]);
366 $destinationRef = $destination->put($data);
367 $this->logger->info('Saved data.', ['newReference' => $destinationRef]);
369 if ($destinationRef !== '') {
370 $this->logger->info('update row');
371 if ($this->dba->update($table, ['backend-class' => $destination::getName(), 'backend-ref' => $destinationRef, 'data' => ''], ['id' => $id])) {
372 if (!empty($source)) {
373 $this->logger->info('Delete data from old backend.', ['oldBackend' => $source, 'oldReference' => $sourceRef]);
374 $source->delete($sourceRef);
381 $this->dba->close($resources);