3 namespace Friendica\Core;
6 use Friendica\Core\Config\IConfig;
7 use Friendica\Database\Database;
8 use Friendica\Model\Storage;
9 use Psr\Log\LoggerInterface;
13 * Manage storage backends
15 * Core code uses this class to get and set current storage backend class.
16 * Addons use this class to register and unregister additional backends.
20 // Default tables to look for data
21 const TABLES = ['photo', 'attach'];
23 // Default storage backends
24 const DEFAULT_BACKENDS = [
25 Storage\Filesystem::NAME => Storage\Filesystem::class,
26 Storage\Database::NAME => Storage\Database::class,
29 private $backends = [];
32 * @var Storage\IStorage[] A local cache for storage instances
34 private $backendInstances = [];
40 /** @var LoggerInterface */
45 /** @var Storage\IStorage */
46 private $currentBackend;
49 * @param Database $dba
50 * @param IConfig $config
51 * @param LoggerInterface $logger
54 public function __construct(Database $dba, IConfig $config, LoggerInterface $logger, L10n $l10n)
57 $this->config = $config;
58 $this->logger = $logger;
60 $this->backends = $config->get('storage', 'backends', self::DEFAULT_BACKENDS);
62 $currentName = $this->config->get('storage', 'name', '');
64 // you can only use user backends as a "default" backend, so the second parameter is true
65 $this->currentBackend = $this->getByName($currentName, true);
69 * Return current storage backend class
71 * @return Storage\IStorage|null
73 public function getBackend()
75 return $this->currentBackend;
79 * Return storage backend class by registered name
81 * @param string|null $name Backend name
82 * @param boolean $onlyUserBackend True, if just user specific instances should be returrned (e.g. not SystemResource)
84 * @return Storage\IStorage|null null if no backend registered at $name
86 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
88 public function getByName(string $name = null, $onlyUserBackend = false)
90 // @todo 2020.09 Remove this call after 2 releases
91 $name = $this->checkLegacyBackend($name);
93 // If there's no cached instance create a new instance
94 if (!isset($this->backendInstances[$name])) {
95 // If the current name isn't a valid backend (or the SystemResource instance) create it
96 if ($this->isValidBackend($name, $onlyUserBackend)) {
98 // Try the filesystem backend
99 case Storage\Filesystem::getName():
100 $this->backendInstances[$name] = new Storage\Filesystem($this->config, $this->logger, $this->l10n);
102 // try the database backend
103 case Storage\Database::getName():
104 $this->backendInstances[$name] = new Storage\Database($this->dba, $this->logger, $this->l10n);
106 // at least, try if there's an addon for the backend
107 case Storage\SystemResource::getName():
108 $this->backendInstances[$name] = new Storage\SystemResource();
115 Hook::callAll('storage_instance', $data);
116 if (($data['storage'] ?? null) instanceof Storage\IStorage) {
117 $this->backendInstances[$data['name'] ?? $name] = $data['storage'];
128 return $this->backendInstances[$name];
132 * Checks, if the storage is a valid backend
134 * @param string|null $name The name or class of the backend
135 * @param boolean $onlyUserBackend True, if just user backend should get returned (e.g. not SystemResource)
137 * @return boolean True, if the backend is a valid backend
139 public function isValidBackend(string $name = null, bool $onlyUserBackend = false)
141 return array_key_exists($name, $this->backends) ||
142 (!$onlyUserBackend && $name === Storage\SystemResource::getName());
146 * Check for legacy backend storage class names (= full model class name)
148 * @todo 2020.09 Remove this function after 2 releases, because there shouldn't be any legacy backend classes left
150 * @param string|null $name a potential, legacy storage name ("Friendica\Model\Storage\...")
152 * @return string|null The current storage name
154 private function checkLegacyBackend(string $name = null)
156 if (stristr($name, 'Friendica\Model\Storage\\')) {
157 $this->logger->notice('Using deprecated storage class value', ['name' => $name]);
158 return substr($name, 24);
165 * Set current storage backend class
167 * @param string $name Backend class name
169 * @return boolean True, if the set was successful
171 public function setBackend(string $name = null)
173 if (!$this->isValidBackend($name, false)) {
177 if ($this->config->set('storage', 'name', $name)) {
178 $this->currentBackend = $this->getByName($name, false);
186 * Get registered backends
190 public function listBackends()
192 return $this->backends;
196 * Register a storage backend class
198 * You have to register the hook "storage_instance" as well to make this class work!
200 * @param string $class Backend class name
202 * @return boolean True, if the registration was successful
204 public function register(string $class)
206 if (is_subclass_of($class, Storage\IStorage::class)) {
207 /** @var Storage\IStorage $class */
209 $backends = $this->backends;
210 $backends[$class::getName()] = $class;
212 if ($this->config->set('storage', 'backends', $backends)) {
213 $this->backends = $backends;
224 * Unregister a storage backend class
226 * @param string $class Backend class name
228 * @return boolean True, if unregistering was successful
230 public function unregister(string $class)
232 if (is_subclass_of($class, Storage\IStorage::class)) {
233 /** @var Storage\IStorage $class */
235 unset($this->backends[$class::getName()]);
237 if ($this->currentBackend instanceof $class) {
238 $this->config->set('storage', 'name', null);
239 $this->currentBackend = null;
242 return $this->config->set('storage', 'backends', $this->backends);
249 * Move up to 5000 resources to storage $dest
251 * Copy existing data to destination storage and delete from source.
252 * This method cannot move to legacy in-table `data` field.
254 * @param Storage\IStorage $destination Destination storage class name
255 * @param array $tables Tables to look in for resources. Optional, defaults to ['photo', 'attach']
256 * @param int $limit Limit of the process batch size, defaults to 5000
258 * @return int Number of moved resources
259 * @throws Storage\StorageException
262 public function move(Storage\IStorage $destination, array $tables = self::TABLES, int $limit = 5000)
264 if (!$this->isValidBackend($destination, true)) {
265 throw new Storage\StorageException(sprintf("Can't move to storage backend '%s'", $destination::getName()));
269 foreach ($tables as $table) {
270 // Get the rows where backend class is not the destination backend class
271 $resources = $this->dba->select(
273 ['id', 'data', 'backend-class', 'backend-ref'],
274 ['`backend-class` IS NULL or `backend-class` != ?', $destination::getName()],
278 while ($resource = $this->dba->fetch($resources)) {
279 $id = $resource['id'];
280 $data = $resource['data'];
281 $source = $this->getByName($resource['backend-class']);
282 $sourceRef = $resource['backend-ref'];
284 if (!empty($source)) {
285 $this->logger->info('Get data from old backend.', ['oldBackend' => $source, 'oldReference' => $sourceRef]);
286 $data = $source->get($sourceRef);
289 $this->logger->info('Save data to new backend.', ['newBackend' => $destination]);
290 $destinationRef = $destination->put($data);
291 $this->logger->info('Saved data.', ['newReference' => $destinationRef]);
293 if ($destinationRef !== '') {
294 $this->logger->info('update row');
295 if ($this->dba->update($table, ['backend-class' => $destination, 'backend-ref' => $destinationRef, 'data' => ''], ['id' => $id])) {
296 if (!empty($source)) {
297 $this->logger->info('Delete data from old backend.', ['oldBackend' => $source, 'oldReference' => $sourceRef]);
298 $source->delete($sourceRef);
305 $this->dba->close($resources);