class CKEditor5ImageController

Same name and namespace in other branches
  1. 10 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 37

Namespace

Drupal\ckeditor5\Controller
View source
class CKEditor5ImageController extends ControllerBase {
  
  /**
   * The file system service.
   *
   * @var \Drupal\Core\File\FileSystem
   */
  protected $fileSystem;
  
  /**
   * The currently authenticated user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;
  
  /**
   * The MIME type guesser.
   *
   * @var \Symfony\Component\Mime\MimeTypeGuesserInterface
   */
  protected $mimeTypeGuesser;
  
  /**
   * The lock service.
   *
   * @var \Drupal\Core\Lock\LockBackendInterface
   */
  protected $lock;
  
  /**
   * The event dispatcher.
   *
   * @var \Symfony\Contracts\EventDispatcher\EventDispatcherInterface
   */
  protected $eventDispatcher;
  
  /**
   * Constructs a new CKEditor5ImageController.
   *
   * @param \Drupal\Core\File\FileSystemInterface $file_system
   *   The file system service.
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   The currently authenticated user.
   * @param \Symfony\Component\Mime\MimeTypeGuesserInterface $mime_type_guesser
   *   The MIME type guesser.
   * @param \Drupal\Core\Lock\LockBackendInterface $lock
   *   The lock service.
   * @param \Symfony\Contracts\EventDispatcher\EventDispatcherInterface $event_dispatcher
   *   The event dispatcher.
   */
  public function __construct(FileSystemInterface $file_system, AccountInterface $current_user, MimeTypeGuesserInterface $mime_type_guesser, LockBackendInterface $lock, EventDispatcherInterface $event_dispatcher) {
    $this->fileSystem = $file_system;
    $this->currentUser = $current_user;
    $this->mimeTypeGuesser = $mime_type_guesser;
    $this->lock = $lock;
    $this->eventDispatcher = $event_dispatcher;
  }
  
  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container->get('file_system'), $container->get('current_user'), $container->get('file.mime_type.guesser'), $container->get('lock'), $container->get('event_dispatcher'));
  }
  
  /**
   * 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.
   * @throws \Drupal\Core\Entity\EntityStorageException
   *   Thrown when file entity could not be saved.
   */
  public function upload(Request $request) {
    // Getting the UploadedFile directly from the request.
    $upload = $request->files
      ->get('upload');
    $filename = $upload->getClientOriginalName();
    $editor = $request->attributes
      ->get('editor');
    $image_upload = $editor->getImageUploadSettings();
    $destination = $image_upload['scheme'] . '://' . $image_upload['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');
    }
    $max_filesize = min(Bytes::toNumber($image_upload['max_size']), Environment::getUploadMaxSize());
    if (!empty($image_upload['max_dimensions']['width']) || !empty($image_upload['max_dimensions']['height'])) {
      $max_dimensions = $image_upload['max_dimensions']['width'] . 'x' . $image_upload['max_dimensions']['height'];
    }
    else {
      $max_dimensions = 0;
    }
    $validators = [
      'file_validate_extensions' => [
        'gif png jpg jpeg',
      ],
      'file_validate_size' => [
        $max_filesize,
      ],
      'file_validate_image_resolution' => [
        $max_dimensions,
      ],
    ];
    $prepared_filename = $this->prepareFilename($filename, $validators);
    // Create the file.
    $file_uri = "{$destination}/{$prepared_filename}";
    // Using the UploadedFile method instead of streamUploadData.
    $temp_file_path = $upload->getRealPath();
    $file_uri = $this->fileSystem
      ->getDestinationFilename($file_uri, FileSystemInterface::EXISTS_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,
      ]);
    }
    // Begin building file entity.
    $file = File::create([]);
    $file->setOwnerId($this->currentUser
      ->id());
    $file->setFilename($prepared_filename);
    if ($this->mimeTypeGuesser instanceof MimeTypeGuesserInterface) {
      $file->setMimeType($this->mimeTypeGuesser
        ->guessMimeType($prepared_filename));
    }
    else {
      $file->setMimeType($this->mimeTypeGuesser
        ->guess($prepared_filename));
      @trigger_error('\\Symfony\\Component\\HttpFoundation\\File\\MimeType\\MimeTypeGuesserInterface is deprecated in drupal:9.1.0 and is removed from drupal:10.0.0. Implement \\Symfony\\Component\\Mime\\MimeTypeGuesserInterface instead. See https://www.drupal.org/node/3133341', E_USER_DEPRECATED);
    }
    $file->setFileUri($file_uri);
    $file->setSize(@filesize($temp_file_path));
    $violations = $this->validate($file, $validators);
    if ($violations->count() > 0) {
      throw new UnprocessableEntityHttpException($violations->__toString());
    }
    try {
      $this->fileSystem
        ->move($temp_file_path, $file_uri, FileSystemInterface::EXISTS_ERROR);
    } catch (FileException $e) {
      throw new HttpException(500, 'Temporary file could not be moved to file location');
    }
    $file->save();
    $this->lock
      ->release($lock_id);
    return new JsonResponse([
      'url' => $file->createFileUrl(),
      'uuid' => $file->uuid(),
      'entity_type' => $file->getEntityTypeId(),
    ], 201);
  }
  
  /**
   * 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();
  }
  
  /**
   * Validates the file.
   *
   * @param \Drupal\file\FileInterface $file
   *   The file entity to validate.
   * @param array $validators
   *   An array of upload validators to pass to file_validate().
   *
   * @return \Drupal\Core\Entity\EntityConstraintViolationListInterface
   *   The list of constraint violations, if any.
   */
  protected function validate(FileInterface $file, array $validators) {
    $violations = $file->validate();
    // Remove violations of inaccessible fields as they cannot stem from our
    // changes.
    $violations->filterByFieldAccess();
    // Validate the file based on the field definition configuration.
    $errors = file_validate($file, $validators);
    if (!empty($errors)) {
      $translator = new DrupalTranslator();
      foreach ($errors as $error) {
        $violation = new ConstraintViolation($translator->trans($error), (string) $error, [], EntityAdapter::createFromEntity($file), '', NULL);
        $violations->add($violation);
      }
    }
    return $violations;
  }
  
  /**
   * Prepares the filename to strip out any malicious extensions.
   *
   * @param string $filename
   *   The file name.
   * @param array $validators
   *   The array of upload validators.
   *
   * @return string
   *   The prepared/munged filename.
   */
  protected function prepareFilename($filename, array &$validators) {
    $extensions = $validators['file_validate_extensions'][0] ?? '';
    $event = new FileUploadSanitizeNameEvent($filename, $extensions);
    $this->eventDispatcher
      ->dispatch($event);
    return $event->getFilename();
  }
  
  /**
   * 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::$currentUser protected property The currently authenticated user. Overrides ControllerBase::$currentUser
CKEditor5ImageController::$eventDispatcher protected property The event dispatcher.
CKEditor5ImageController::$fileSystem protected property The file system service.
CKEditor5ImageController::$lock protected property The lock service.
CKEditor5ImageController::$mimeTypeGuesser protected property The MIME type guesser.
CKEditor5ImageController::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
CKEditor5ImageController::generateLockIdFromFileUri protected static function Generates a lock ID based on the file URI.
CKEditor5ImageController::imageUploadEnabledAccess public function Access check based on whether image upload is enabled or not.
CKEditor5ImageController::prepareFilename protected function Prepares the filename to strip out any malicious extensions.
CKEditor5ImageController::upload public function Uploads and saves an image from a CKEditor 5 POST.
CKEditor5ImageController::validate protected function Validates the file.
CKEditor5ImageController::__construct public function Constructs a new CKEditor5ImageController.
ControllerBase::$configFactory protected property The configuration factory.
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. 3
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. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
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.