class CKEditor5ImageController

Same name in other branches
  1. 9 core/modules/ckeditor5/src/Controller/CKEditor5ImageController.php \Drupal\ckeditor5\Controller\CKEditor5ImageController
  2. 10 core/modules/ckeditor5/src/Controller/CKEditor5ImageController.php \Drupal\ckeditor5\Controller\CKEditor5ImageController

Returns response for CKEditor 5 Simple image upload adapter.

@internal Controller classes are internal.

Hierarchy

Expanded class hierarchy of CKEditor5ImageController

File

core/modules/ckeditor5/src/Controller/CKEditor5ImageController.php, line 35

Namespace

Drupal\ckeditor5\Controller
View source
class CKEditor5ImageController extends ControllerBase {
    
    /**
     * Constructs a new CKEditor5ImageController.
     *
     * @param \Drupal\Core\File\FileSystemInterface $fileSystem
     *   The file system service.
     * @param \Drupal\file\Upload\FileUploadHandler $fileUploadHandler
     *   The file upload handler.
     * @param \Drupal\Core\Lock\LockBackendInterface $lock
     *   The lock service.
     * @param \Drupal\ckeditor5\Plugin\CKEditor5PluginManagerInterface $pluginManager
     *   The CKEditor 5 plugin manager.
     */
    public function __construct(FileSystemInterface $fileSystem, FileUploadHandler $fileUploadHandler, LockBackendInterface $lock, CKEditor5PluginManagerInterface $pluginManager) {
    }
    
    /**
     * {@inheritdoc}
     */
    public static function create(ContainerInterface $container) {
        return new static($container->get('file_system'), $container->get('file.upload_handler'), $container->get('lock'), $container->get('plugin.manager.ckeditor5.plugin'));
    }
    
    /**
     * Uploads and saves an image from a CKEditor 5 POST.
     *
     * @param \Symfony\Component\HttpFoundation\Request $request
     *   The current request object.
     *
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     *   A JSON object including the file URL.
     *
     * @throws \Symfony\Component\HttpKernel\Exception\HttpException
     *   Thrown when file system errors occur.
     * @throws \Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException
     *   Thrown when validation errors occur.
     */
    public function upload(Request $request) : Response {
        // Getting the UploadedFile directly from the request.
        
        /** @var \Symfony\Component\HttpFoundation\File\UploadedFile|null $upload */
        $upload = $request->files
            ->get('upload');
        if ($upload === NULL || !$upload->isValid()) {
            throw new HttpException(500, $upload?->getErrorMessage() ?: 'Invalid file upload');
        }
        $filename = $upload->getClientOriginalName();
        
        /** @var \Drupal\editor\EditorInterface $editor */
        $editor = $request->attributes
            ->get('editor');
        $settings = $editor->getImageUploadSettings();
        $destination = $settings['scheme'] . '://' . $settings['directory'];
        // Check the destination file path is writable.
        if (!$this->fileSystem
            ->prepareDirectory($destination, FileSystemInterface::CREATE_DIRECTORY)) {
            throw new HttpException(500, 'Destination file path is not writable');
        }
        $validators = $this->getImageUploadValidators($settings);
        $file_uri = "{$destination}/{$filename}";
        $file_uri = $this->fileSystem
            ->getDestinationFilename($file_uri, FileExists::Rename);
        // Lock based on the prepared file URI.
        $lock_id = $this->generateLockIdFromFileUri($file_uri);
        if (!$this->lock
            ->acquire($lock_id)) {
            throw new HttpException(503, sprintf('File "%s" is already locked for writing.', $file_uri), NULL, [
                'Retry-After' => 1,
            ]);
        }
        try {
            $uploadedFile = new FormUploadedFile($upload);
            $uploadResult = $this->fileUploadHandler
                ->handleFileUpload($uploadedFile, $validators, $destination, FileExists::Rename);
            if ($uploadResult->hasViolations()) {
                throw new UnprocessableEntityHttpException((string) $uploadResult->getViolations());
            }
        } catch (FileException) {
            throw new HttpException(500, 'File could not be saved');
        } catch (LockAcquiringException) {
            throw new HttpException(503, sprintf('File "%s" is already locked for writing.', $upload->getClientOriginalName()), NULL, [
                'Retry-After' => 1,
            ]);
        }
        $this->lock
            ->release($lock_id);
        $file = $uploadResult->getFile();
        return new JsonResponse([
            'url' => $file->createFileUrl(),
            'uuid' => $file->uuid(),
            'entity_type' => $file->getEntityTypeId(),
        ], 201);
    }
    
    /**
     * Gets the image upload validators.
     */
    protected function getImageUploadValidators(array $settings) : array {
        $max_filesize = $settings['max_size'] ? Bytes::toNumber($settings['max_size']) : Environment::getUploadMaxSize();
        $max_dimensions = 0;
        if (!empty($settings['max_dimensions']['width']) || !empty($settings['max_dimensions']['height'])) {
            $max_dimensions = $settings['max_dimensions']['width'] . 'x' . $settings['max_dimensions']['height'];
        }
        $mimetypes = MimeTypes::getDefault();
        $imageUploadPlugin = $this->pluginManager
            ->getDefinition('ckeditor5_imageUpload')
            ->toArray();
        $allowed_extensions = [];
        foreach ($imageUploadPlugin['ckeditor5']['config']['image']['upload']['types'] as $mime_type) {
            $allowed_extensions = array_merge($allowed_extensions, $mimetypes->getExtensions('image/' . $mime_type));
        }
        return [
            'FileExtension' => [
                'extensions' => implode(' ', $allowed_extensions),
            ],
            'FileSizeLimit' => [
                'fileLimit' => $max_filesize,
            ],
            'FileImageDimensions' => [
                'maxDimensions' => $max_dimensions,
            ],
        ];
    }
    
    /**
     * Access check based on whether image upload is enabled or not.
     *
     * @param \Drupal\editor\Entity\Editor $editor
     *   The text editor for which an image upload is occurring.
     *
     * @return \Drupal\Core\Access\AccessResultInterface
     *   The access result.
     */
    public function imageUploadEnabledAccess(Editor $editor) {
        if ($editor->getEditor() !== 'ckeditor5') {
            return AccessResult::forbidden();
        }
        if ($editor->getImageUploadSettings()['status'] !== TRUE) {
            return AccessResult::forbidden();
        }
        return AccessResult::allowed();
    }
    
    /**
     * Generates a lock ID based on the file URI.
     *
     * @param string $file_uri
     *   The file URI.
     *
     * @return string
     *   The generated lock ID.
     */
    protected static function generateLockIdFromFileUri($file_uri) {
        return 'file:ckeditor5:' . Crypt::hashBase64($file_uri);
    }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title Overrides
CKEditor5ImageController::create public static function Instantiates a new instance of the implementing class using autowiring. Overrides AutowireTrait::create
CKEditor5ImageController::generateLockIdFromFileUri protected static function Generates a lock ID based on the file URI.
CKEditor5ImageController::getImageUploadValidators protected function Gets the image upload validators.
CKEditor5ImageController::imageUploadEnabledAccess public function Access check based on whether image upload is enabled or not.
CKEditor5ImageController::upload public function Uploads and saves an image from a CKEditor 5 POST.
CKEditor5ImageController::__construct public function Constructs a new CKEditor5ImageController.
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 2
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 1
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 1
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::currentUser protected function Returns the current user. 2
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 1
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 1
ControllerBase::redirect protected function Returns a redirect response object for the specified route.
ControllerBase::state protected function Returns the state storage service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 16
MessengerTrait::messenger public function Gets the messenger. 16
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 2
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 3
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.