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\IHTTPRequest;
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 */
64 /** @var IHTTPRequest */
67 /** @var Storage\IStorage */
68 private $currentBackend;
71 * @param Database $dba
72 * @param IConfig $config
73 * @param LoggerInterface $logger
76 public function __construct(Database $dba, IConfig $config, LoggerInterface $logger, L10n $l10n, IHTTPRequest $httpRequest)
79 $this->config = $config;
80 $this->logger = $logger;
82 $this->httpRequest = $httpRequest;
83 $this->backends = $config->get('storage', 'backends', self::DEFAULT_BACKENDS);
85 $currentName = $this->config->get('storage', 'name', '');
87 // you can only use user backends as a "default" backend, so the second parameter is true
88 $this->currentBackend = $this->getByName($currentName, true);
92 * Return current storage backend class
94 * @return Storage\IStorage|null
96 public function getBackend()
98 return $this->currentBackend;
102 * Return storage backend class by registered name
104 * @param string|null $name Backend name
105 * @param boolean $onlyUserBackend True, if just user specific instances should be returrned (e.g. not SystemResource)
107 * @return Storage\IStorage|null null if no backend registered at $name
109 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
111 public function getByName(string $name = null, $onlyUserBackend = false)
113 // @todo 2020.09 Remove this call after 2 releases
114 $name = $this->checkLegacyBackend($name);
116 // If there's no cached instance create a new instance
117 if (!isset($this->backendInstances[$name])) {
118 // If the current name isn't a valid backend (or the SystemResource instance) create it
119 if ($this->isValidBackend($name, $onlyUserBackend)) {
121 // Try the filesystem backend
122 case Storage\Filesystem::getName():
123 $this->backendInstances[$name] = new Storage\Filesystem($this->config, $this->logger, $this->l10n);
125 // try the database backend
126 case Storage\Database::getName():
127 $this->backendInstances[$name] = new Storage\Database($this->dba, $this->logger, $this->l10n);
129 // at least, try if there's an addon for the backend
130 case Storage\SystemResource::getName():
131 $this->backendInstances[$name] = new Storage\SystemResource();
133 case Storage\ExternalResource::getName():
134 $this->backendInstances[$name] = new Storage\ExternalResource($this->httpRequest);
141 Hook::callAll('storage_instance', $data);
142 if (($data['storage'] ?? null) instanceof Storage\IStorage) {
143 $this->backendInstances[$data['name'] ?? $name] = $data['storage'];
154 return $this->backendInstances[$name];
158 * Checks, if the storage is a valid backend
160 * @param string|null $name The name or class of the backend
161 * @param boolean $onlyUserBackend True, if just user backend should get returned (e.g. not SystemResource)
163 * @return boolean True, if the backend is a valid backend
165 public function isValidBackend(string $name = null, bool $onlyUserBackend = false)
167 return array_key_exists($name, $this->backends) ||
168 (!$onlyUserBackend && in_array($name, [Storage\SystemResource::getName(), Storage\ExternalResource::getName()]));
172 * Check for legacy backend storage class names (= full model class name)
174 * @todo 2020.09 Remove this function after 2 releases, because there shouldn't be any legacy backend classes left
176 * @param string|null $name a potential, legacy storage name ("Friendica\Model\Storage\...")
178 * @return string|null The current storage name
180 private function checkLegacyBackend(string $name = null)
182 if (stristr($name, 'Friendica\Model\Storage\\')) {
183 $this->logger->notice('Using deprecated storage class value', ['name' => $name]);
184 return substr($name, 24);
191 * Set current storage backend class
193 * @param string $name Backend class name
195 * @return boolean True, if the set was successful
197 public function setBackend(string $name = null)
199 if (!$this->isValidBackend($name, false)) {
203 if ($this->config->set('storage', 'name', $name)) {
204 $this->currentBackend = $this->getByName($name, false);
212 * Get registered backends
216 public function listBackends()
218 return $this->backends;
222 * Register a storage backend class
224 * You have to register the hook "storage_instance" as well to make this class work!
226 * @param string $class Backend class name
228 * @return boolean True, if the registration was successful
230 public function register(string $class)
232 if (is_subclass_of($class, Storage\IStorage::class)) {
233 /** @var Storage\IStorage $class */
235 $backends = $this->backends;
236 $backends[$class::getName()] = $class;
238 if ($this->config->set('storage', 'backends', $backends)) {
239 $this->backends = $backends;
250 * Unregister a storage backend class
252 * @param string $class Backend class name
254 * @return boolean True, if unregistering was successful
256 public function unregister(string $class)
258 if (is_subclass_of($class, Storage\IStorage::class)) {
259 /** @var Storage\IStorage $class */
261 unset($this->backends[$class::getName()]);
263 if ($this->currentBackend instanceof $class) {
264 $this->config->set('storage', 'name', null);
265 $this->currentBackend = null;
268 return $this->config->set('storage', 'backends', $this->backends);
275 * Move up to 5000 resources to storage $dest
277 * Copy existing data to destination storage and delete from source.
278 * This method cannot move to legacy in-table `data` field.
280 * @param Storage\IStorage $destination Destination storage class name
281 * @param array $tables Tables to look in for resources. Optional, defaults to ['photo', 'attach']
282 * @param int $limit Limit of the process batch size, defaults to 5000
284 * @return int Number of moved resources
285 * @throws Storage\StorageException
288 public function move(Storage\IStorage $destination, array $tables = self::TABLES, int $limit = 5000)
290 if (!$this->isValidBackend($destination, true)) {
291 throw new Storage\StorageException(sprintf("Can't move to storage backend '%s'", $destination::getName()));
295 foreach ($tables as $table) {
296 // Get the rows where backend class is not the destination backend class
297 $resources = $this->dba->select(
299 ['id', 'data', 'backend-class', 'backend-ref'],
300 ['`backend-class` IS NULL or `backend-class` != ?', $destination::getName()],
304 while ($resource = $this->dba->fetch($resources)) {
305 $id = $resource['id'];
306 $data = $resource['data'];
307 $source = $this->getByName($resource['backend-class']);
308 $sourceRef = $resource['backend-ref'];
310 if (!empty($source)) {
311 $this->logger->info('Get data from old backend.', ['oldBackend' => $source, 'oldReference' => $sourceRef]);
312 $data = $source->get($sourceRef);
315 $this->logger->info('Save data to new backend.', ['newBackend' => $destination::getName()]);
316 $destinationRef = $destination->put($data);
317 $this->logger->info('Saved data.', ['newReference' => $destinationRef]);
319 if ($destinationRef !== '') {
320 $this->logger->info('update row');
321 if ($this->dba->update($table, ['backend-class' => $destination::getName(), 'backend-ref' => $destinationRef, 'data' => ''], ['id' => $id])) {
322 if (!empty($source)) {
323 $this->logger->info('Delete data from old backend.', ['oldBackend' => $source, 'oldReference' => $sourceRef]);
324 $source->delete($sourceRef);
331 $this->dba->close($resources);