]> git.mxchange.org Git - friendica.git/blobdiff - src/Model/Storage/Filesystem.php
Insert a `user-contact` for every contact
[friendica.git] / src / Model / Storage / Filesystem.php
index bb68731cd04510168367e988968cd08f774b517b..c6c939bd464353154eab1193916cdd2c79ecb1d9 100644 (file)
@@ -1,18 +1,33 @@
 <?php
 /**
- * @file src/Model/Storage/Filesystem.php
- * @brief Storage backend system
+ * @copyright Copyright (C) 2010-2021, the Friendica project
+ *
+ * @license GNU AGPL version 3 or any later version
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program.  If not, see <https://www.gnu.org/licenses/>.
+ *
  */
 
 namespace Friendica\Model\Storage;
 
-use Friendica\Core\Config;
+use Exception;
+use Friendica\Core\Config\IConfig;
 use Friendica\Core\L10n;
-use Friendica\Core\Logger;
 use Friendica\Util\Strings;
 
 /**
- * @brief Filesystem based storage backend
+ * Filesystem based storage backend
  *
  * This class manage data on filesystem.
  * Base folder for storage is set in storage.filesystem_path.
@@ -21,120 +36,187 @@ use Friendica\Util\Strings;
  * Each new resource gets a value as reference and is saved in a
  * folder tree stucture created from that value.
  */
-class Filesystem implements IStorage
+class Filesystem implements IWritableStorage
 {
+       const NAME = 'Filesystem';
+
        // Default base folder
        const DEFAULT_BASE_FOLDER = 'storage';
 
-       private static function getBasePath()
+       /** @var IConfig */
+       private $config;
+
+       /** @var string */
+       private $basePath;
+
+       /** @var L10n */
+       private $l10n;
+
+       /**
+        * Filesystem constructor.
+        *
+        * @param IConfig         $config
+        * @param L10n            $l10n
+        */
+       public function __construct(IConfig $config, L10n $l10n)
        {
-               return Config::get('storage', 'filesystem_path', self::DEFAULT_BASE_FOLDER);
+               $this->config = $config;
+               $this->l10n   = $l10n;
+
+               $path           = $this->config->get('storage', 'filesystem_path', self::DEFAULT_BASE_FOLDER);
+               $this->basePath = rtrim($path, '/');
        }
 
        /**
-        * @brief Split data ref and return file path
-        * @param string  $ref  Data reference
+        * Split data ref and return file path
+        *
+        * @param string $reference Data reference
+        *
         * @return string
         */
-       private static function pathForRef($ref)
+       private function pathForRef(string $reference): string
        {
-               $base = self::getBasePath();
-               $fold1 = substr($ref, 0, 2);
-               $fold2 = substr($ref, 2, 2);
-               $file = substr($ref, 4);
+               $fold1 = substr($reference, 0, 2);
+               $fold2 = substr($reference, 2, 2);
+               $file  = substr($reference, 4);
 
-               return implode('/', [$base, $fold1, $fold2, $file]);
+               return implode('/', [$this->basePath, $fold1, $fold2, $file]);
        }
 
 
        /**
-        * @brief Create dirctory tree to store file, with .htaccess and index.html files
+        * Create directory tree to store file, with .htaccess and index.html files
+        *
         * @param string $file Path and filename
+        *
         * @throws StorageException
         */
-       private static function createFoldersForFile($file)
+       private function createFoldersForFile(string $file)
        {
                $path = dirname($file);
 
                if (!is_dir($path)) {
                        if (!mkdir($path, 0770, true)) {
-                               Logger::log('Failed to create dirs ' . $path);
-                               throw new StorageException(L10n::t('Filesystem storage failed to create "%s". Check you write permissions.', $path));
+                               throw new StorageException(sprintf('Filesystem storage failed to create "%s". Check you write permissions.', $path));
                        }
                }
 
-               $base = self::getBasePath();
-
-               while ($path !== $base) {
+               while ($path !== $this->basePath) {
                        if (!is_file($path . '/index.html')) {
                                file_put_contents($path . '/index.html', '');
                        }
+                       chmod($path . '/index.html', 0660);
+                       chmod($path, 0770);
                        $path = dirname($path);
                }
                if (!is_file($path . '/index.html')) {
                        file_put_contents($path . '/index.html', '');
+                       chmod($path . '/index.html', 0660);
                }
        }
 
-       public static function get($ref)
+       /**
+        * @inheritDoc
+        */
+       public function get(string $reference): string
        {
-               $file = self::pathForRef($ref);
+               $file = $this->pathForRef($reference);
                if (!is_file($file)) {
-                       return '';
+                       throw new ReferenceStorageException(sprintf('Filesystem storage failed to get the file %s, The file is invalid', $reference));
                }
 
-               return file_get_contents($file);
+               $result = file_get_contents($file);
+
+               if ($result === false) {
+                       throw new StorageException(sprintf('Filesystem storage failed to get data to "%s". Check your write permissions', $file));
+               }
+
+               return $result;
        }
 
-       public static function put($data, $ref = '')
+       /**
+        * @inheritDoc
+        */
+       public function put(string $data, string $reference = ''): string
        {
-               if ($ref === '') {
-                       $ref = Strings::getRandomHex();
+               if ($reference === '') {
+                       try {
+                               $reference = Strings::getRandomHex();
+                       } catch (Exception $exception) {
+                               throw new StorageException('Filesystem storage failed to generate a random hex', $exception->getCode(), $exception);
+                       }
                }
-               $file = self::pathForRef($ref);
+               $file = $this->pathForRef($reference);
+
+               $this->createFoldersForFile($file);
 
-               self::createFoldersForFile($file);
+               $result = file_put_contents($file, $data);
 
-               $r = file_put_contents($file, $data);
-               if ($r === FALSE) {
-                       Logger::log('Failed to write data to ' . $file);
-                       throw new StorageException(L10n::t('Filesystem storage failed to save data to "%s". Check your write permissions', $file));
+               // just in case the result is REALLY false, not zero or empty or anything else, throw the exception
+               if ($result === false) {
+                       throw new StorageException(sprintf('Filesystem storage failed to save data to "%s". Check your write permissions', $file));
                }
-               return $ref;
+
+               chmod($file, 0660);
+               return $reference;
        }
 
-       public static function delete($ref)
+       /**
+        * @inheritDoc
+        */
+       public function delete(string $reference)
        {
-               $file = self::pathForRef($ref);
-               // return true if file doesn't exists. we want to delete it: success with zero work!
+               $file = $this->pathForRef($reference);
                if (!is_file($file)) {
-                       return true;
+                       throw new ReferenceStorageException(sprintf('File with reference "%s" doesn\'t exist', $reference));
+               }
+
+               if (!unlink($file)) {
+                       throw new StorageException(sprintf('Cannot delete with file with reference "%s"', $reference));
                }
-               return unlink($file);
        }
 
-       public static function getOptions()
+       /**
+        * @inheritDoc
+        */
+       public function getOptions(): array
        {
                return [
                        'storagepath' => [
                                'input',
-                               L10n::t('Storage base path'),
-                               self::getBasePath(),
-                               L10n::t('Folder were uploaded files are saved. For maximum security, This should be a path outside web server folder tree')
+                               $this->l10n->t('Storage base path'),
+                               $this->basePath,
+                               $this->l10n->t('Folder where uploaded files are saved. For maximum security, This should be a path outside web server folder tree')
                        ]
                ];
        }
-       
-       public static function saveOptions($data)
+
+       /**
+        * @inheritDoc
+        */
+       public function saveOptions(array $data): array
        {
-               $storagepath = defaults($data, 'storagepath', '');
-               if ($storagepath === '' || !is_dir($storagepath)) {
+               $storagePath = $data['storagepath'] ?? '';
+               if ($storagePath === '' || !is_dir($storagePath)) {
                        return [
-                               'storagepath' => L10n::t('Enter a valid existing folder')
+                               'storagepath' => $this->l10n->t('Enter a valid existing folder')
                        ];
                };
-               Config::set('storage', 'filesystem_path', $storagepath);
+               $this->config->set('storage', 'filesystem_path', $storagePath);
+               $this->basePath = $storagePath;
                return [];
        }
 
+       /**
+        * @inheritDoc
+        */
+       public static function getName(): string
+       {
+               return self::NAME;
+       }
+
+       public function __toString()
+       {
+               return self::getName();
+       }
 }