3 namespace Friendica\Core;
6 use Friendica\Core\Config\IConfiguration;
7 use Friendica\Core\L10n\L10n;
8 use Friendica\Database\Database;
9 use Friendica\Model\Storage;
10 use Psr\Log\LoggerInterface;
14 * @brief Manage storage backends
16 * Core code uses this class to get and set current storage backend class.
17 * Addons use this class to register and unregister additional backends.
21 // Default tables to look for data
22 const TABLES = ['photo', 'attach'];
24 // Default storage backends
25 const DEFAULT_BACKENDS = [
26 Storage\Filesystem::NAME => Storage\Filesystem::class,
27 Storage\Database::NAME => Storage\Database::class,
30 private $backends = [];
33 * @var Storage\IStorage[] A local cache for storage instances
35 private $backendInstances = [];
39 /** @var IConfiguration */
41 /** @var LoggerInterface */
46 /** @var Storage\IStorage */
47 private $currentBackend;
50 * @param Database $dba
51 * @param IConfiguration $config
52 * @param LoggerInterface $logger
55 public function __construct(Database $dba, IConfiguration $config, LoggerInterface $logger, L10n $l10n)
58 $this->config = $config;
59 $this->logger = $logger;
61 $this->backends = $config->get('storage', 'backends', self::DEFAULT_BACKENDS);
63 $currentName = $this->config->get('storage', 'name', '');
65 // you can only use user backends as a "default" backend, so the second parameter is true
66 $this->currentBackend = $this->getByName($currentName, true);
70 * @brief Return current storage backend class
72 * @return Storage\IStorage|null
74 public function getBackend()
76 return $this->currentBackend;
80 * @brief Return storage backend class by registered name
82 * @param string|null $name Backend name
83 * @param boolean $onlyUserBackend True, if just user specific instances should be returrned (e.g. not SystemResource)
85 * @return Storage\IStorage|null null if no backend registered at $name
87 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
89 public function getByName(string $name = null, $onlyUserBackend = false)
91 // If there's no cached instance create a new instance
92 if (!isset($this->backendInstances[$name])) {
93 // If the current name isn't a valid backend (or the SystemResource instance) create it
94 if ($this->isValidBackend($name, $onlyUserBackend)) {
96 // Try the filesystem backend
97 case Storage\Filesystem::getName():
98 $this->backendInstances[$name] = new Storage\Filesystem($this->config, $this->logger, $this->l10n);
100 // try the database backend
101 case Storage\Database::getName():
102 $this->backendInstances[$name] = new Storage\Database($this->dba, $this->logger, $this->l10n);
104 // at least, try if there's an addon for the backend
105 case Storage\SystemResource::getName():
106 $this->backendInstances[$name] = new Storage\SystemResource();
113 Hook::callAll('storage_instance', $data);
114 if (($data['storage'] ?? null) instanceof Storage\IStorage) {
115 $this->backendInstances[$data['name'] ?? $name] = $data['storage'];
126 return $this->backendInstances[$name];
130 * Checks, if the storage is a valid backend
132 * @param string|null $name The name or class of the backend
133 * @param boolean $onlyUserBackend True, if just user backend should get returned (e.g. not SystemResource)
135 * @return boolean True, if the backend is a valid backend
137 public function isValidBackend(string $name = null, bool $onlyUserBackend = false)
139 return array_key_exists($name, $this->backends) ||
140 (!$onlyUserBackend && $name === Storage\SystemResource::getName());
144 * @brief Set current storage backend class
146 * @param string $name Backend class name
148 * @return boolean True, if the set was successful
150 public function setBackend(string $name = null)
152 if (!$this->isValidBackend($name, false)) {
156 if ($this->config->set('storage', 'name', $name)) {
157 $this->currentBackend = $this->getByName($name, false);
165 * @brief Get registered backends
169 public function listBackends()
171 return $this->backends;
175 * Register a storage backend class
177 * You have to register the hook "storage_instance" as well to make this class work!
179 * @param string $class Backend class name
181 * @return boolean True, if the registration was successful
183 public function register(string $class)
185 if (is_subclass_of($class, Storage\IStorage::class)) {
186 /** @var Storage\IStorage $class */
188 $backends = $this->backends;
189 $backends[$class::getName()] = $class;
191 if ($this->config->set('storage', 'backends', $backends)) {
192 $this->backends = $backends;
203 * @brief Unregister a storage backend class
205 * @param string $class Backend class name
207 * @return boolean True, if unregistering was successful
209 public function unregister(string $class)
211 if (is_subclass_of($class, Storage\IStorage::class)) {
212 /** @var Storage\IStorage $class */
214 unset($this->backends[$class::getName()]);
216 if ($this->currentBackend instanceof $class) {
217 $this->config->set('storage', 'name', null);
218 $this->currentBackend = null;
221 return $this->config->set('storage', 'backends', $this->backends);
228 * @brief Move up to 5000 resources to storage $dest
230 * Copy existing data to destination storage and delete from source.
231 * This method cannot move to legacy in-table `data` field.
233 * @param Storage\IStorage $destination Destination storage class name
234 * @param array $tables Tables to look in for resources. Optional, defaults to ['photo', 'attach']
235 * @param int $limit Limit of the process batch size, defaults to 5000
237 * @return int Number of moved resources
238 * @throws Storage\StorageException
241 public function move(Storage\IStorage $destination, array $tables = self::TABLES, int $limit = 5000)
243 if ($destination === null) {
244 throw new Storage\StorageException('Can\'t move to NULL storage backend');
248 foreach ($tables as $table) {
249 // Get the rows where backend class is not the destination backend class
250 $resources = $this->dba->select(
252 ['id', 'data', 'backend-class', 'backend-ref'],
253 ['`backend-class` IS NULL or `backend-class` != ?', $destination::getName()],
257 while ($resource = $this->dba->fetch($resources)) {
258 $id = $resource['id'];
259 $data = $resource['data'];
260 $source = $this->getByName($resource['backend-class']);
261 $sourceRef = $resource['backend-ref'];
263 if (!empty($source)) {
264 $this->logger->info('Get data from old backend.', ['oldBackend' => $source, 'oldReference' => $sourceRef]);
265 $data = $source->get($sourceRef);
268 $this->logger->info('Save data to new backend.', ['newBackend' => $destination]);
269 $destinationRef = $destination->put($data);
270 $this->logger->info('Saved data.', ['newReference' => $destinationRef]);
272 if ($destinationRef !== '') {
273 $this->logger->info('update row');
274 if ($this->dba->update($table, ['backend-class' => $destination, 'backend-ref' => $destinationRef, 'data' => ''], ['id' => $id])) {
275 if (!empty($source)) {
276 $this->logger->info('Delete data from old backend.', ['oldBackend' => $source, 'oldReference' => $sourceRef]);
277 $source->delete($sourceRef);
284 $this->dba->close($resources);