You are here

class CKEditorUploadImageController in CKEditor Upload Image 8

Same name and namespace in other branches
  1. 8.2 src/Controller/CKEditorUploadImageController.php \Drupal\ckeditor_uploadimage\Controller\CKEditorUploadImageController

Hierarchy

Expanded class hierarchy of CKEditorUploadImageController

File

src/Controller/CKEditorUploadImageController.php, line 14
Contains \Drupal\ckeditor_uploadimage\Controller\CKEditorUploadImageController.

Namespace

Drupal\ckeditor_uploadimage\Controller
View source
class CKEditorUploadImageController extends ControllerBase {

  /**
   * Save uploaded file via CKEditor uploadimage plugin.
   */
  public function saveFile(Request $request) {
    $status = TRUE;
    $errorMsg = '';
    $defaultResponsiveImageStyle = '';
    $filterFormatId = $request->query
      ->get('filterFormatId');
    $editor = editor_load($filterFormatId);

    // Construct strings to use in the upload validators.
    $imageUpload = $editor
      ->getImageUploadSettings();
    if (!empty($imageUpload['max_dimensions']['width']) || !empty($imageUpload['max_dimensions']['height'])) {
      $maxDimensions = $imageUpload['max_dimensions']['width'] . 'x' . $imageUpload['max_dimensions']['height'];
    }
    else {
      $maxDimensions = 0;
    }
    $maxFilesize = min(Bytes::toInt($imageUpload['max_size']), file_upload_max_size());
    $destination = $imageUpload['scheme'] . '://' . $imageUpload['directory'];

    /** @var \Drupal\Core\File\FileSystemInterface $fileSystem */
    $fileSystem = \Drupal::service('file_system');
    if (isset($destination) && !file_prepare_directory($destination, FILE_CREATE_DIRECTORY)) {
      \Drupal::logger('ckeditor_uploadimage')
        ->notice('The upload directory %directory for the file field %name could not be
        created or is not accessible. A newly uploaded file could not be saved
        in this directory as a consequence, and the upload was canceled.', [
        '%directory' => $destination,
        '%name' => 'fid',
      ]);
      $errorMsg = $this
        ->t('The file could not be uploaded.');
      $status = FALSE;
    }
    else {
      $validators = [
        'file_validate_extensions' => [
          'gif png jpg jpeg',
        ],
        'file_validate_size' => [
          $maxFilesize,
        ],
        'file_validate_image_resolution' => [
          $maxDimensions,
        ],
      ];
      $files = $request->files
        ->get('files', array());
      if (!isset($files['fid'])) {
        $files = $request->files
          ->all();
        $request->files
          ->set('files', [
          'fid' => $files['upload'],
        ]);
      }
      $file = file_save_upload('fid', $validators, $destination);
      $messages = drupal_get_messages();
      if (isset($messages['error'])) {

        /** @var \Drupal\Core\Render\Markup $message */
        foreach ($messages['error'] as $message) {
          $errorMsg = '<div>' . $message
            ->jsonSerialize() . '</div>';
        }
      }
      if (isset($messages['warning'])) {

        /** @var \Drupal\Core\Render\Markup $message */
        foreach ($messages['warning'] as $message) {
          $errorMsg .= '<div>' . $message
            ->jsonSerialize() . '</div>';
        }
      }
      if (isset($messages['status'])) {

        /** @var \Drupal\Core\Render\Markup $message */
        foreach ($messages['status'] as $message) {
          $errorMsg .= '<div>' . $message
            ->jsonSerialize() . '</div>';
        }
      }
      if (!empty($errorMsg)) {
        $errorMsg = "<div style='text-align: left;'>{$errorMsg}</div>";
      }
      if (!empty($file[0])) {
        $origFileName = $file[0]
          ->getFilename();
        $alt = pathinfo($origFileName, PATHINFO_FILENAME);
        $alt = str_replace('_', ' ', $alt);
        $uri = $file[0]
          ->getFileUri();
        $uuid = $file[0]
          ->uuid();
        $fileName = $fileSystem
          ->basename($uri);
        $url = file_url_transform_relative(file_create_url($uri));
        $entityType = $file[0]
          ->getEntityTypeId();
        $moduleHandler = \Drupal::service('module_handler');
        if ($moduleHandler
          ->moduleExists('inline_responsive_images')) {

          // Get a responsive image style.
          $responsiveImage = $editor
            ->getFilterFormat()
            ->filters('filter_responsive_image_style');
          $responsiveImageSettings = $responsiveImage
            ->getConfiguration();
          foreach ($responsiveImageSettings['settings'] as $responsiveImageStyle => $enabled) {
            if ($enabled == '1') {

              // Make the first responsive image style as default.
              $defaultResponsiveImageStyle = str_replace('responsive_style_', '', $responsiveImageStyle);
              break;
            }
          }
        }
        if ($moduleHandler
          ->moduleExists('media')) {
          $mediaImageFields = \Drupal::service('entity_field.manager')
            ->getFieldDefinitions('media', 'image');
          if (isset($mediaImageFields['field_media_image']) && $imageUpload['media_entity_image']) {

            // Create media entity with saved file.
            $imageMedia = \Drupal\media\Entity\Media::create([
              'bundle' => 'image',
              'name' => $alt,
              'uid' => \Drupal::currentUser()
                ->id(),
              'langcode' => \Drupal::languageManager()
                ->getDefaultLanguage()
                ->getId(),
              'status' => \Drupal\node\NodeInterface::PUBLISHED,
              'thumbnail' => [
                'target_id' => $file[0]
                  ->id(),
              ],
              'field_media_image' => [
                0 => [
                  'target_id' => $file[0]
                    ->id(),
                  'alt' => $alt,
                ],
              ],
            ]);
            $imageMedia
              ->save();
          }
        }
      }
      else {
        $status = FALSE;
      }
    }
    if (!$status) {
      $json = [
        'uploaded' => $status,
        'error' => [
          'message' => $errorMsg,
        ],
      ];
    }
    else {
      $json = [
        'uploaded' => $status,
        'fileName' => $fileName,
        'url' => $url,
        'alt' => $alt,
        'entityUuid' => $uuid,
        'entityType' => $entityType,
        'responsiveImageStyle' => $defaultResponsiveImageStyle,
        'error' => [
          'message' => $errorMsg,
        ],
      ];
    }
    return new JsonResponse($json);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CKEditorUploadImageController::saveFile public function Save uploaded file via CKEditor uploadimage plugin.
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityManager protected property The entity manager.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
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::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 40
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityManager Deprecated protected function Retrieves the entity manager service.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
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. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
ControllerBase::state protected function Returns the state storage service.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator 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. 29
MessengerTrait::messenger public function Gets the messenger. 29
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. 1
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.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.