Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Public Member Functions | Data Fields | Protected Member Functions | Protected Attributes
Storage Class Reference
Inheritance diagram for Storage:
DataObject

Public Member Functions

 __construct (\Magento\Backend\Model\Session $session, \Magento\Backend\Model\UrlInterface $backendUrl, \Magento\Cms\Helper\Wysiwyg\Images $cmsWysiwygImages, \Magento\MediaStorage\Helper\File\Storage\Database $coreFileStorageDb, \Magento\Framework\Filesystem $filesystem, \Magento\Framework\Image\AdapterFactory $imageFactory, \Magento\Framework\View\Asset\Repository $assetRepo, \Magento\Cms\Model\Wysiwyg\Images\Storage\CollectionFactory $storageCollectionFactory, \Magento\MediaStorage\Model\File\Storage\FileFactory $storageFileFactory, \Magento\MediaStorage\Model\File\Storage\DatabaseFactory $storageDatabaseFactory, \Magento\MediaStorage\Model\File\Storage\Directory\DatabaseFactory $directoryDatabaseFactory, \Magento\MediaStorage\Model\File\UploaderFactory $uploaderFactory, array $resizeParameters=[], array $extensions=[], array $dirs=[], array $data=[])
 
 getDirsCollection ($path)
 
 createDirectory ($name, $path)
 
 deleteDirectory ($path)
 
 deleteFile ($target)
 
 getThumbnailPath ($filePath, $checkFile=false)
 
 getThumbnailUrl ($filePath, $checkFile=false)
 
 resizeFile ($source, $keepRatio=true)
 
 resizeOnTheFly ($filename)
 
 getThumbsPath ($filePath=false)
 
 getSession ()
 
 getAllowedExtensions ($type=null)
 
 getThumbnailRoot ()
 
 isImage ($filename)
 
 getResizeWidth ()
 
 getResizeHeight ()
 
 getCmsWysiwygImages ()
 
- Public Member Functions inherited from DataObject
 __construct (array $data=[])
 
 addData (array $arr)
 
 setData ($key, $value=null)
 
 unsetData ($key=null)
 
 getData ($key='', $index=null)
 
 getDataByPath ($path)
 
 getDataByKey ($key)
 
 setDataUsingMethod ($key, $args=[])
 
 getDataUsingMethod ($key, $args=null)
 
 hasData ($key='')
 
 toArray (array $keys=[])
 
 convertToArray (array $keys=[])
 
 toXml (array $keys=[], $rootName='item', $addOpenTag=false, $addCdata=true)
 
 convertToXml (array $arrAttributes=[], $rootName='item', $addOpenTag=false, $addCdata=true)
 
 toJson (array $keys=[])
 
 convertToJson (array $keys=[])
 
 toString ($format='')
 
 __call ($method, $args)
 
 isEmpty ()
 
 serialize ($keys=[], $valueSeparator='=', $fieldSeparator=' ', $quote='"')
 
 debug ($data=null, &$objects=[])
 
 offsetSet ($offset, $value)
 
 offsetExists ($offset)
 
 offsetUnset ($offset)
 
 offsetGet ($offset)
 

Data Fields

const DIRECTORY_NAME_REGEXP = '/^[a-z0-9\-\_]+$/si'
 
const THUMBS_DIRECTORY_NAME = '.thumbs'
 
const THUMB_PLACEHOLDER_PATH_SUFFIX = 'Magento_Cms::images/placeholder_thumbnail.jpg'
 

Protected Member Functions

 getConditionsForExcludeDirs ()
 
 removeItemFromCollection ($collection, $conditions)
 
 _deleteByPath ($path)
 
 _validatePath ($path)
 
 _sanitizePath ($path)
 
 _getRelativePathToRoot ($path)
 
- Protected Member Functions inherited from DataObject
 _getData ($key)
 
 _underscore ($name)
 

Protected Attributes

 $_config
 
 $_configAsArray
 
 $_directory
 
 $_imageFactory
 
 $_assetRepo
 
 $_coreFileStorageDb = null
 
 $_cmsWysiwygImages = null
 
 $_resizeParameters
 
 $_extensions
 
 $_dirs
 
 $_backendUrl
 
 $_session
 
 $_directoryDatabaseFactory
 
 $_storageDatabaseFactory
 
 $_storageFileFactory
 
 $_storageCollectionFactory
 
 $_uploaderFactory
 
- Protected Attributes inherited from DataObject
 $_data = []
 

Additional Inherited Members

- Static Protected Attributes inherited from DataObject
static $_underscoreCache = []
 

Detailed Description

Wysiwyg Images model

@SuppressWarnings(PHPMD.LongVariable) @SuppressWarnings(PHPMD.TooManyFields) @SuppressWarnings(PHPMD.CouplingBetweenObjects)

@api

Since
100.0.2

Definition at line 21 of file Storage.php.

Constructor & Destructor Documentation

◆ __construct()

__construct ( \Magento\Backend\Model\Session  $session,
\Magento\Backend\Model\UrlInterface  $backendUrl,
\Magento\Cms\Helper\Wysiwyg\Images  $cmsWysiwygImages,
\Magento\MediaStorage\Helper\File\Storage\Database  $coreFileStorageDb,
\Magento\Framework\Filesystem  $filesystem,
\Magento\Framework\Image\AdapterFactory  $imageFactory,
\Magento\Framework\View\Asset\Repository  $assetRepo,
\Magento\Cms\Model\Wysiwyg\Images\Storage\CollectionFactory  $storageCollectionFactory,
\Magento\MediaStorage\Model\File\Storage\FileFactory  $storageFileFactory,
\Magento\MediaStorage\Model\File\Storage\DatabaseFactory  $storageDatabaseFactory,
\Magento\MediaStorage\Model\File\Storage\Directory\DatabaseFactory  $directoryDatabaseFactory,
\Magento\MediaStorage\Model\File\UploaderFactory  $uploaderFactory,
array  $resizeParameters = [],
array  $extensions = [],
array  $dirs = [],
array  $data = [] 
)

Construct

Parameters
\Magento\Backend\Model\Session$session
\Magento\Backend\Model\UrlInterface$backendUrl
\Magento\Cms\Helper\Wysiwyg\Images$cmsWysiwygImages
\Magento\MediaStorage\Helper\File\Storage\Database$coreFileStorageDb
\Magento\Framework\Filesystem$filesystem
\Magento\Framework\Image\AdapterFactory$imageFactory
\Magento\Framework\View\Asset\Repository$assetRepo
\Magento\Cms\Model\Wysiwyg\Images\Storage\CollectionFactory$storageCollectionFactory
\Magento\MediaStorage\Model\File\Storage\FileFactory$storageFileFactory
\Magento\MediaStorage\Model\File\Storage\DatabaseFactory$storageDatabaseFactory
\Magento\MediaStorage\Model\File\Storage\Directory\DatabaseFactory$directoryDatabaseFactory
\Magento\MediaStorage\Model\File\UploaderFactory$uploaderFactory
array$resizeParameters
array$extensions
array$dirs
array$data@SuppressWarnings(PHPMD.ExcessiveParameterList)

Definition at line 154 of file Storage.php.

171  {
172  $this->_session = $session;
173  $this->_backendUrl = $backendUrl;
174  $this->_cmsWysiwygImages = $cmsWysiwygImages;
175  $this->_coreFileStorageDb = $coreFileStorageDb;
176  $this->_directory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA);
177  $this->_imageFactory = $imageFactory;
178  $this->_assetRepo = $assetRepo;
179  $this->_storageCollectionFactory = $storageCollectionFactory;
180  $this->_storageFileFactory = $storageFileFactory;
181  $this->_storageDatabaseFactory = $storageDatabaseFactory;
182  $this->_directoryDatabaseFactory = $directoryDatabaseFactory;
183  $this->_uploaderFactory = $uploaderFactory;
184  $this->_resizeParameters = $resizeParameters;
185  $this->_extensions = $extensions;
186  $this->_dirs = $dirs;
187  parent::__construct($data);
188  }
$filesystem

Member Function Documentation

◆ _deleteByPath()

_deleteByPath (   $path)
protected

Delete by path

Parameters
string$path
Returns
void

Definition at line 440 of file Storage.php.

441  {
442  $path = $this->_sanitizePath($path);
443  if (!empty($path)) {
444  $this->_validatePath($path);
445  $this->_directory->delete($this->_directory->getRelativePath($path));
446  }
447  }

◆ _getRelativePathToRoot()

_getRelativePathToRoot (   $path)
protected

Get path in root storage dir

Parameters
string$path
Returns
string|bool

Definition at line 742 of file Storage.php.

743  {
744  return substr(
745  $this->_sanitizePath($path),
746  strlen($this->_sanitizePath($this->_cmsWysiwygImages->getStorageRoot()))
747  );
748  }

◆ _sanitizePath()

_sanitizePath (   $path)
protected

Sanitize path

Parameters
string$path
Returns
string

Definition at line 731 of file Storage.php.

732  {
733  return rtrim(preg_replace('~[/\\\]+~', '/', $this->_directory->getDriver()->getRealPathSafety($path)), '/');
734  }

◆ _validatePath()

_validatePath (   $path)
protected

Is path under storage root directory

Parameters
string$path
Returns
void
Exceptions

Definition at line 710 of file Storage.php.

711  {
712  $root = $this->_sanitizePath($this->_cmsWysiwygImages->getStorageRoot());
713  if ($root == $path) {
714  throw new \Magento\Framework\Exception\LocalizedException(
715  __('We can\'t delete root directory %1 right now.', $path)
716  );
717  }
718  if (strpos($path, $root) !== 0) {
719  throw new \Magento\Framework\Exception\LocalizedException(
720  __('Directory %1 is not under storage root path.', $path)
721  );
722  }
723  }
__()
Definition: __.php:13

◆ createDirectory()

createDirectory (   $name,
  $path 
)

Create new directory in storage

Parameters
string$nameNew directory name
string$pathParent directory path
Returns
array New directory info
Exceptions

Definition at line 373 of file Storage.php.

374  {
375  if (!preg_match(self::DIRECTORY_NAME_REGEXP, $name)) {
376  throw new \Magento\Framework\Exception\LocalizedException(
377  __('Please rename the folder using only letters, numbers, underscores and dashes.')
378  );
379  }
380 
381  $relativePath = $this->_directory->getRelativePath($path);
382  if (!$this->_directory->isDirectory($relativePath) || !$this->_directory->isWritable($relativePath)) {
383  $path = $this->_cmsWysiwygImages->getStorageRoot();
384  }
385 
386  $newPath = $path . '/' . $name;
387  $relativeNewPath = $this->_directory->getRelativePath($newPath);
388  if ($this->_directory->isDirectory($relativeNewPath)) {
389  throw new \Magento\Framework\Exception\LocalizedException(
390  __('We found a directory with the same name. Please try another folder name.')
391  );
392  }
393 
394  $this->_directory->create($relativeNewPath);
395  try {
396  if ($this->_coreFileStorageDb->checkDbUsage()) {
397  $relativePath = $this->_coreFileStorageDb->getMediaRelativePath($newPath);
398  $this->_directoryDatabaseFactory->create()->createRecursive($relativePath);
399  }
400 
401  $result = [
402  'name' => $name,
403  'short_name' => $this->_cmsWysiwygImages->getShortFilename($name),
404  'path' => $newPath,
405  'id' => $this->_cmsWysiwygImages->convertPathToId($newPath),
406  ];
407  return $result;
408  } catch (\Magento\Framework\Exception\FileSystemException $e) {
409  throw new \Magento\Framework\Exception\LocalizedException(__('We cannot create a new directory.'));
410  }
411  }
__()
Definition: __.php:13
$relativePath
Definition: get.php:35
if(!isset($_GET['name'])) $name
Definition: log.php:14

◆ deleteDirectory()

deleteDirectory (   $path)

Recursively delete directory from storage

Parameters
string$pathTarget dir
Returns
void
Exceptions

Definition at line 420 of file Storage.php.

421  {
422  if ($this->_coreFileStorageDb->checkDbUsage()) {
423  $this->_directoryDatabaseFactory->create()->deleteDirectory($path);
424  }
425  try {
426  $this->_deleteByPath($path);
427  $path = $this->getThumbnailRoot() . $this->_getRelativePathToRoot($path);
428  $this->_deleteByPath($path);
429  } catch (\Magento\Framework\Exception\FileSystemException $e) {
430  throw new \Magento\Framework\Exception\LocalizedException(__('We cannot delete directory %1.', $path));
431  }
432  }
__()
Definition: __.php:13

◆ deleteFile()

deleteFile (   $target)

Delete file (and its thumbnail if exists) from storage

Parameters
string$targetFile path to be deleted
Returns
$this

Definition at line 455 of file Storage.php.

456  {
457  $relativePath = $this->_directory->getRelativePath($target);
458  if ($this->_directory->isFile($relativePath)) {
459  $this->_directory->delete($relativePath);
460  }
461  $this->_coreFileStorageDb->deleteFile($target);
462 
463  $thumb = $this->getThumbnailPath($target, true);
464  $relativePathThumb = $this->_directory->getRelativePath($thumb);
465  if ($thumb) {
466  if ($this->_directory->isFile($relativePathThumb)) {
467  $this->_directory->delete($relativePathThumb);
468  }
469  $this->_coreFileStorageDb->deleteFile($thumb);
470  }
471  return $this;
472  }
getThumbnailPath($filePath, $checkFile=false)
Definition: Storage.php:514
$target
Definition: skip.phtml:8
$relativePath
Definition: get.php:35

◆ getAllowedExtensions()

getAllowedExtensions (   $type = null)

Prepare allowed_extensions config settings

Parameters
string$typeType of storage, e.g. image, media etc.
Returns
array Array of allowed file extensions

Definition at line 641 of file Storage.php.

642  {
643  $allowed = $this->getExtensionsList($type);
644 
645  return array_keys(array_filter($allowed));
646  }
$type
Definition: item.phtml:13

◆ getCmsWysiwygImages()

getCmsWysiwygImages ( )

Get cms wysiwyg images helper

Returns
Images|null

Definition at line 698 of file Storage.php.

◆ getConditionsForExcludeDirs()

getConditionsForExcludeDirs ( )
protected

Prepare and get conditions for exclude directories

Returns
array

Definition at line 214 of file Storage.php.

215  {
216  $conditions = ['reg_exp' => [], 'plain' => []];
217 
218  if ($this->_dirs['exclude']) {
219  foreach ($this->_dirs['exclude'] as $dir) {
220  $conditions[!empty($dir['regexp']) ? 'reg_exp' : 'plain'][$dir['name']] = true;
221  }
222  }
223 
224  // "include" section takes precedence and can revoke directory exclusion
225  if ($this->_dirs['include']) {
226  foreach ($this->_dirs['include'] as $dir) {
227  unset($conditions['reg_exp'][$dir['name']], $conditions['plain'][$dir['name']]);
228  }
229  }
230 
231  return $conditions;
232  }

◆ getDirsCollection()

getDirsCollection (   $path)

Return one-level child directories for specified path

Parameters
string$pathParent directory path
Returns
\Magento\Framework\Data\Collection\Filesystem

Definition at line 266 of file Storage.php.

267  {
268  $this->createSubDirectories($path);
269 
270  $collection = $this->getCollection($path)
271  ->setCollectDirs(true)
272  ->setCollectFiles(false)
273  ->setCollectRecursively(false);
274 
275  $conditions = $this->getConditionsForExcludeDirs();
276 
277  return $this->removeItemFromCollection($collection, $conditions);
278  }
removeItemFromCollection($collection, $conditions)
Definition: Storage.php:241

◆ getResizeHeight()

getResizeHeight ( )

Get resize height

Returns
int

Definition at line 688 of file Storage.php.

689  {
690  return $this->_resizeParameters['height'];
691  }

◆ getResizeWidth()

getResizeWidth ( )

Get resize width

Returns
int

Definition at line 678 of file Storage.php.

679  {
680  return $this->_resizeParameters['width'];
681  }

◆ getSession()

getSession ( )

Storage session

Returns
\Magento\Backend\Model\Session

Definition at line 630 of file Storage.php.

631  {
632  return $this->_session;
633  }

◆ getThumbnailPath()

getThumbnailPath (   $filePath,
  $checkFile = false 
)

Thumbnail path getter

Parameters
string$filePathoriginal file path
bool$checkFileOPTIONAL is it necessary to check file availability
Returns
string|false

Definition at line 514 of file Storage.php.

515  {
516  $mediaRootDir = $this->_cmsWysiwygImages->getStorageRoot();
517 
518  if (strpos($filePath, $mediaRootDir) === 0) {
519  $thumbPath = $this->getThumbnailRoot() . substr($filePath, strlen($mediaRootDir));
520 
521  if (!$checkFile || $this->_directory->isExist($this->_directory->getRelativePath($thumbPath))) {
522  return $thumbPath;
523  }
524  }
525 
526  return false;
527  }

◆ getThumbnailRoot()

getThumbnailRoot ( )

Thumbnail root directory getter

Returns
string

Definition at line 653 of file Storage.php.

654  {
655  return $this->_cmsWysiwygImages->getStorageRoot() . '/' . self::THUMBS_DIRECTORY_NAME;
656  }

◆ getThumbnailUrl()

getThumbnailUrl (   $filePath,
  $checkFile = false 
)

Thumbnail URL getter

Parameters
string$filePathoriginal file path
bool$checkFileOPTIONAL is it necessary to check file availability
Returns
string|false

Definition at line 536 of file Storage.php.

537  {
538  $mediaRootDir = $this->_cmsWysiwygImages->getStorageRoot();
539 
540  if (strpos($filePath, $mediaRootDir) === 0) {
541  $thumbSuffix = self::THUMBS_DIRECTORY_NAME . substr($filePath, strlen($mediaRootDir));
542  if (!$checkFile || $this->_directory->isExist(
543  $this->_directory->getRelativePath($mediaRootDir . '/' . $thumbSuffix)
544  )
545  ) {
546  $thumbSuffix = substr(
547  $mediaRootDir,
548  strlen($this->_directory->getAbsolutePath())
549  ) . '/' . $thumbSuffix;
550  $randomIndex = '?rand=' . time();
551  return str_replace('\\', '/', $this->_cmsWysiwygImages->getBaseUrl() . $thumbSuffix) . $randomIndex;
552  }
553  }
554 
555  return false;
556  }

◆ getThumbsPath()

getThumbsPath (   $filePath = false)

Return thumbnails directory path for file/current directory

Parameters
bool | string$filePathPath to the file
Returns
string

Definition at line 613 of file Storage.php.

614  {
615  $mediaRootDir = $this->_cmsWysiwygImages->getStorageRoot();
616  $thumbnailDir = $this->getThumbnailRoot();
617 
618  if ($filePath && strpos($filePath, $mediaRootDir) === 0) {
619  $thumbnailDir .= dirname(substr($filePath, strlen($mediaRootDir)));
620  }
621 
622  return $thumbnailDir;
623  }

◆ isImage()

isImage (   $filename)

Simple way to check whether file is image or not based on extension

Parameters
string$filename
Returns
bool

Definition at line 664 of file Storage.php.

665  {
666  if (!$this->hasData('_image_extensions')) {
667  $this->setData('_image_extensions', $this->getAllowedExtensions('image'));
668  }
669  $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
670  return in_array($ext, $this->_getData('_image_extensions'));
671  }
setData($key, $value=null)
Definition: DataObject.php:72

◆ removeItemFromCollection()

removeItemFromCollection (   $collection,
  $conditions 
)
protected

Remove excluded directories from collection

Parameters
\Magento\Framework\Data\Collection\Filesystem$collection
array$conditions
Returns
\Magento\Framework\Data\Collection\Filesystem

Definition at line 241 of file Storage.php.

242  {
243  $regExp = $conditions['reg_exp'] ? '~' . implode('|', array_keys($conditions['reg_exp'])) . '~i' : null;
244  $storageRoot = $this->_cmsWysiwygImages->getStorageRoot();
245  $storageRootLength = strlen($storageRoot);
246 
247  foreach ($collection as $key => $value) {
248  $mediaSubPathname = substr($value->getFilename(), $storageRootLength);
249  $rootChildParts = explode('/', '/' . ltrim($mediaSubPathname, '/'));
250 
251  if (array_key_exists($rootChildParts[1], $conditions['plain'])
252  || ($regExp && preg_match($regExp, $value->getFilename()))) {
253  $collection->removeItemByKey($key);
254  }
255  }
256 
257  return $collection;
258  }
$value
Definition: gender.phtml:16

◆ resizeFile()

resizeFile (   $source,
  $keepRatio = true 
)

Create thumbnail for image and save it to thumbnails directory

Parameters
string$sourceImage path to be resized
bool$keepRatioKeep aspect ratio or not
Returns
bool|string Resized filepath or false if errors were occurred

Definition at line 565 of file Storage.php.

566  {
567  $realPath = $this->_directory->getRelativePath($source);
568  if (!$this->_directory->isFile($realPath) || !$this->_directory->isExist($realPath)) {
569  return false;
570  }
571 
572  $targetDir = $this->getThumbsPath($source);
573  $pathTargetDir = $this->_directory->getRelativePath($targetDir);
574  if (!$this->_directory->isExist($pathTargetDir)) {
575  $this->_directory->create($pathTargetDir);
576  }
577  if (!$this->_directory->isExist($pathTargetDir)) {
578  return false;
579  }
580  $image = $this->_imageFactory->create();
581  $image->open($source);
582  $image->keepAspectRatio($keepRatio);
583  $image->resize($this->_resizeParameters['width'], $this->_resizeParameters['height']);
584  $dest = $targetDir . '/' . pathinfo($source, PATHINFO_BASENAME);
585  $image->save($dest);
586  if ($this->_directory->isFile($this->_directory->getRelativePath($dest))) {
587  return $dest;
588  }
589  return false;
590  }
$source
Definition: source.php:23

◆ resizeOnTheFly()

resizeOnTheFly (   $filename)

Resize images on the fly in controller action

Parameters
string$filenameFile basename
Returns
bool|string Thumbnail path or false for errors

Definition at line 598 of file Storage.php.

599  {
600  $path = $this->getSession()->getCurrentPath();
601  if (!$path) {
602  $path = $this->_cmsWysiwygImages->getCurrentPath();
603  }
604  return $this->resizeFile($path . '/' . $filename);
605  }
resizeFile($source, $keepRatio=true)
Definition: Storage.php:565

Field Documentation

◆ $_assetRepo

$_assetRepo
protected

Definition at line 56 of file Storage.php.

◆ $_backendUrl

$_backendUrl
protected

Definition at line 90 of file Storage.php.

◆ $_cmsWysiwygImages

$_cmsWysiwygImages = null
protected

Definition at line 70 of file Storage.php.

◆ $_config

$_config
protected

Definition at line 34 of file Storage.php.

◆ $_configAsArray

$_configAsArray
protected

Definition at line 41 of file Storage.php.

◆ $_coreFileStorageDb

$_coreFileStorageDb = null
protected

Definition at line 63 of file Storage.php.

◆ $_directory

$_directory
protected

Definition at line 46 of file Storage.php.

◆ $_directoryDatabaseFactory

$_directoryDatabaseFactory
protected

Definition at line 102 of file Storage.php.

◆ $_dirs

$_dirs
protected

Definition at line 85 of file Storage.php.

◆ $_extensions

$_extensions
protected

Definition at line 80 of file Storage.php.

◆ $_imageFactory

$_imageFactory
protected

Definition at line 51 of file Storage.php.

◆ $_resizeParameters

$_resizeParameters
protected

Definition at line 75 of file Storage.php.

◆ $_session

$_session
protected

Definition at line 95 of file Storage.php.

◆ $_storageCollectionFactory

$_storageCollectionFactory
protected

Definition at line 123 of file Storage.php.

◆ $_storageDatabaseFactory

$_storageDatabaseFactory
protected

Definition at line 109 of file Storage.php.

◆ $_storageFileFactory

$_storageFileFactory
protected

Definition at line 116 of file Storage.php.

◆ $_uploaderFactory

$_uploaderFactory
protected

Definition at line 130 of file Storage.php.

◆ DIRECTORY_NAME_REGEXP

const DIRECTORY_NAME_REGEXP = '/^[a-z0-9\-\_]+$/si'

Definition at line 23 of file Storage.php.

◆ THUMB_PLACEHOLDER_PATH_SUFFIX

const THUMB_PLACEHOLDER_PATH_SUFFIX = 'Magento_Cms::images/placeholder_thumbnail.jpg'

Definition at line 27 of file Storage.php.

◆ THUMBS_DIRECTORY_NAME

const THUMBS_DIRECTORY_NAME = '.thumbs'

Definition at line 25 of file Storage.php.


The documentation for this class was generated from the following file: