3 * @copyright Copyright (C) 2020, Friendica
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 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
43 const DEFAULT_BACKENDS = [
44 Storage\Filesystem::NAME => Storage\Filesystem::class,
45 Storage\Database::NAME => Storage\Database::class,
48 private $backends = [];
51 * @var Storage\IStorage[] A local cache for storage instances
53 private $backendInstances = [];
59 /** @var LoggerInterface */
64 /** @var Storage\IStorage */
65 private $currentBackend;
68 * @param Database $dba
69 * @param IConfig $config
70 * @param LoggerInterface $logger
73 public function __construct(Database $dba, IConfig $config, LoggerInterface $logger, L10n $l10n)
76 $this->config = $config;
77 $this->logger = $logger;
79 $this->backends = $config->get('storage', 'backends', self::DEFAULT_BACKENDS);
81 $currentName = $this->config->get('storage', 'name', '');
83 // you can only use user backends as a "default" backend, so the second parameter is true
84 $this->currentBackend = $this->getByName($currentName, true);
88 * Return current storage backend class
90 * @return Storage\IStorage|null
92 public function getBackend()
94 return $this->currentBackend;
98 * Return storage backend class by registered name
100 * @param string|null $name Backend name
101 * @param boolean $onlyUserBackend True, if just user specific instances should be returrned (e.g. not SystemResource)
103 * @return Storage\IStorage|null null if no backend registered at $name
105 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
107 public function getByName(string $name = null, $onlyUserBackend = false)
109 // @todo 2020.09 Remove this call after 2 releases
110 $name = $this->checkLegacyBackend($name);
112 // If there's no cached instance create a new instance
113 if (!isset($this->backendInstances[$name])) {
114 // If the current name isn't a valid backend (or the SystemResource instance) create it
115 if ($this->isValidBackend($name, $onlyUserBackend)) {
117 // Try the filesystem backend
118 case Storage\Filesystem::getName():
119 $this->backendInstances[$name] = new Storage\Filesystem($this->config, $this->logger, $this->l10n);
121 // try the database backend
122 case Storage\Database::getName():
123 $this->backendInstances[$name] = new Storage\Database($this->dba, $this->logger, $this->l10n);
125 // at least, try if there's an addon for the backend
126 case Storage\SystemResource::getName():
127 $this->backendInstances[$name] = new Storage\SystemResource();
134 Hook::callAll('storage_instance', $data);
135 if (($data['storage'] ?? null) instanceof Storage\IStorage) {
136 $this->backendInstances[$data['name'] ?? $name] = $data['storage'];
147 return $this->backendInstances[$name];
151 * Checks, if the storage is a valid backend
153 * @param string|null $name The name or class of the backend
154 * @param boolean $onlyUserBackend True, if just user backend should get returned (e.g. not SystemResource)
156 * @return boolean True, if the backend is a valid backend
158 public function isValidBackend(string $name = null, bool $onlyUserBackend = false)
160 return array_key_exists($name, $this->backends) ||
161 (!$onlyUserBackend && $name === Storage\SystemResource::getName());
165 * Check for legacy backend storage class names (= full model class name)
167 * @todo 2020.09 Remove this function after 2 releases, because there shouldn't be any legacy backend classes left
169 * @param string|null $name a potential, legacy storage name ("Friendica\Model\Storage\...")
171 * @return string|null The current storage name
173 private function checkLegacyBackend(string $name = null)
175 if (stristr($name, 'Friendica\Model\Storage\\')) {
176 $this->logger->notice('Using deprecated storage class value', ['name' => $name]);
177 return substr($name, 24);
184 * Set current storage backend class
186 * @param string $name Backend class name
188 * @return boolean True, if the set was successful
190 public function setBackend(string $name = null)
192 if (!$this->isValidBackend($name, false)) {
196 if ($this->config->set('storage', 'name', $name)) {
197 $this->currentBackend = $this->getByName($name, false);
205 * Get registered backends
209 public function listBackends()
211 return $this->backends;
215 * Register a storage backend class
217 * You have to register the hook "storage_instance" as well to make this class work!
219 * @param string $class Backend class name
221 * @return boolean True, if the registration was successful
223 public function register(string $class)
225 if (is_subclass_of($class, Storage\IStorage::class)) {
226 /** @var Storage\IStorage $class */
228 $backends = $this->backends;
229 $backends[$class::getName()] = $class;
231 if ($this->config->set('storage', 'backends', $backends)) {
232 $this->backends = $backends;
243 * Unregister a storage backend class
245 * @param string $class Backend class name
247 * @return boolean True, if unregistering was successful
249 public function unregister(string $class)
251 if (is_subclass_of($class, Storage\IStorage::class)) {
252 /** @var Storage\IStorage $class */
254 unset($this->backends[$class::getName()]);
256 if ($this->currentBackend instanceof $class) {
257 $this->config->set('storage', 'name', null);
258 $this->currentBackend = null;
261 return $this->config->set('storage', 'backends', $this->backends);
268 * Move up to 5000 resources to storage $dest
270 * Copy existing data to destination storage and delete from source.
271 * This method cannot move to legacy in-table `data` field.
273 * @param Storage\IStorage $destination Destination storage class name
274 * @param array $tables Tables to look in for resources. Optional, defaults to ['photo', 'attach']
275 * @param int $limit Limit of the process batch size, defaults to 5000
277 * @return int Number of moved resources
278 * @throws Storage\StorageException
281 public function move(Storage\IStorage $destination, array $tables = self::TABLES, int $limit = 5000)
283 if (!$this->isValidBackend($destination, true)) {
284 throw new Storage\StorageException(sprintf("Can't move to storage backend '%s'", $destination::getName()));
288 foreach ($tables as $table) {
289 // Get the rows where backend class is not the destination backend class
290 $resources = $this->dba->select(
292 ['id', 'data', 'backend-class', 'backend-ref'],
293 ['`backend-class` IS NULL or `backend-class` != ?', $destination::getName()],
297 while ($resource = $this->dba->fetch($resources)) {
298 $id = $resource['id'];
299 $data = $resource['data'];
300 $source = $this->getByName($resource['backend-class']);
301 $sourceRef = $resource['backend-ref'];
303 if (!empty($source)) {
304 $this->logger->info('Get data from old backend.', ['oldBackend' => $source, 'oldReference' => $sourceRef]);
305 $data = $source->get($sourceRef);
308 $this->logger->info('Save data to new backend.', ['newBackend' => $destination]);
309 $destinationRef = $destination->put($data);
310 $this->logger->info('Saved data.', ['newReference' => $destinationRef]);
312 if ($destinationRef !== '') {
313 $this->logger->info('update row');
314 if ($this->dba->update($table, ['backend-class' => $destination, 'backend-ref' => $destinationRef, 'data' => ''], ['id' => $id])) {
315 if (!empty($source)) {
316 $this->logger->info('Delete data from old backend.', ['oldBackend' => $source, 'oldReference' => $sourceRef]);
317 $source->delete($sourceRef);
324 $this->dba->close($resources);