class CKEditor5ImageController

Same name in other branches
  1. 9 core/modules/ckeditor5/src/Controller/CKEditor5ImageController.php \Drupal\ckeditor5\Controller\CKEditor5ImageController
  2. 11.x 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 39

Namespace

Drupal\ckeditor5\Controller
View source
class CKEditor5ImageController extends ControllerBase {
    
    /**
     * The default allowed image extensions.
     *
     * @deprecated in drupal:10.3.0 and is removed from drupal:11.0.0 without replacement.
     *
     * @see https://www.drupal.org/node/3384728
     */
    const DEFAULT_IMAGE_EXTENSIONS = 'gif png jpg jpeg';
    
    /**
     * The file system service.
     */
    protected FileSystemInterface $fileSystem;
    
    /**
     * The lock.
     */
    protected LockBackendInterface $lock;
    
    /**
     * The file upload handler.
     */
    protected FileUploadHandler $fileUploadHandler;
    
    /**
     * The CKEditor 5 plugin manager.
     */
    protected CKEditor5PluginManagerInterface $pluginManager;
    
    /**
     * Constructs a new CKEditor5ImageController.
     *
     * @param \Drupal\Core\File\FileSystemInterface $fileSystem
     *   The file system service.
     * @param \Drupal\Core\Session\AccountInterface|\Drupal\file\Upload\FileUploadHandler $fileUploadHandler
     *   The file upload handler.
     * @param \Symfony\Component\Mime\MimeTypeGuesserInterface|\Drupal\Core\Lock\LockBackendInterface $mime_type_guesser
     *   The lock service.
     * @param \Drupal\Core\Lock\LockBackendInterface|\Drupal\ckeditor5\Plugin\CKEditor5PluginManagerInterface $pluginManager
     *   The CKEditor 5 plugin manager.
     * @param \Symfony\Contracts\EventDispatcher\EventDispatcherInterface|null $event_dispatcher
     *   The event dispatcher.
     * @param \Drupal\file\Validation\FileValidatorInterface|null $file_validator
     *   The file validator.
     */
    public function __construct(FileSystemInterface $fileSystem, AccountInterface|FileUploadHandler $fileUploadHandler, MimeTypeGuesserInterface|LockBackendInterface $mime_type_guesser, LockBackendInterface|CKEditor5PluginManagerInterface $pluginManager, ?EventDispatcherInterface $event_dispatcher = NULL, ?FileValidatorInterface $file_validator = NULL) {
        $this->fileSystem = $fileSystem;
        if ($fileUploadHandler instanceof AccountInterface) {
            @trigger_error('Calling ' . __METHOD__ . '() with the $current_user argument is deprecated in drupal:10.3.0 and is removed from drupal:11.0.0. See https://www.drupal.org/node/3388990', E_USER_DEPRECATED);
            $fileUploadHandler = \Drupal::service('file.upload_handler');
        }
        $this->fileUploadHandler = $fileUploadHandler;
        if ($mime_type_guesser instanceof MimeTypeGuesserInterface) {
            @trigger_error('Calling ' . __METHOD__ . '() with the $mime_type_guesser argument is deprecated in drupal:10.3.0 and is replaced with $lock from drupal:11.0.0. See https://www.drupal.org/node/3388990', E_USER_DEPRECATED);
            $mime_type_guesser = \Drupal::service('lock');
        }
        $this->lock = $mime_type_guesser;
        if ($pluginManager instanceof LockBackendInterface) {
            @trigger_error('Calling ' . __METHOD__ . '() with the $lock argument in position 4 is deprecated in drupal:10.3.0 and is required in drupal:11.0.0. See https://www.drupal.org/node/3384728', E_USER_DEPRECATED);
            $pluginManager = \Drupal::service('plugin.manager.ckeditor5.plugin');
        }
        $this->pluginManager = $pluginManager;
        if ($event_dispatcher) {
            @trigger_error('Calling ' . __METHOD__ . '() with the $event_dispatcher argument is deprecated in drupal:10.3.0 and is removed from drupal:11.0.0. See https://www.drupal.org/node/3388990', E_USER_DEPRECATED);
        }
        if ($file_validator) {
            @trigger_error('Calling ' . __METHOD__ . '() with the $file_validator argument is deprecated in drupal:10.3.0 and is removed from drupal:11.0.0. See https://www.drupal.org/node/3388990', E_USER_DEPRECATED);
        }
    }
    
    /**
     * {@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, FALSE);
            if ($uploadResult->hasViolations()) {
                throw new UnprocessableEntityHttpException((string) $uploadResult->getViolations());
            }
        } catch (FileException $e) {
            throw new HttpException(500, 'File could not be saved');
        } catch (LockAcquiringException $e) {
            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 Deprecated Modifiers Object type Summary Overriden Title Overrides
CKEditor5ImageController::$fileSystem protected property The file system service.
CKEditor5ImageController::$fileUploadHandler protected property The file upload handler.
CKEditor5ImageController::$lock protected property The lock.
CKEditor5ImageController::$pluginManager protected property The CKEditor 5 plugin manager.
CKEditor5ImageController::create public static function Instantiates a new instance of the implementing class using autowiring. Overrides AutowireTrait::create
CKEditor5ImageController::DEFAULT_IMAGE_EXTENSIONS Deprecated constant The default allowed image extensions.
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.