getImageUploadSettings example


  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'];
    }
    
protected function isPluginDisabled(CKEditor5PluginInterface $plugin, EditorInterface $editor): bool {
    assert($plugin->getPluginDefinition()->hasConditions());
    foreach ($plugin->getPluginDefinition()->getConditions() as $condition_type => $required_value) {
      switch ($condition_type) {
        case 'toolbarItem':
          if (!in_array($required_value$editor->getSettings()['toolbar']['items'])) {
            return TRUE;
          }
          break;

        case 'imageUploadStatus':
          $image_upload_status = $editor->getImageUploadSettings()['status'] ?? FALSE;
          return $image_upload_status !== $required_value;

        case 'filter':
          $filters = $editor->getFilterFormat()->filters();
          assert($filters instanceof FilterPluginCollection);
          if (!$filters->has($required_value) || !$filters->get($required_value)->status) {
            return TRUE;
          }
          break;

        case 'requiresConfiguration':
          
// Only update if the editor is using the `uploadImage` toolbar item.     $settings = $editor->getSettings();
    if (is_array($settings['toolbar']['items']) && in_array('uploadImage', $settings['toolbar']['items'], TRUE)) {
      // Replace `uploadImage` with `drupalInsertImage`.       $settings['toolbar']['items'] = str_replace('uploadImage', 'drupalInsertImage', $settings['toolbar']['items']);
      // `<img data-entity-uuid data-entity-type>` are implicitly supported when       // uploads are enabled as the attributes are necessary for upload       // functionality. If uploads aren't enabled, these attributes must still       // be supported to ensure existing content that may have them (despite       // uploads being disabled) remains editable. In this use case, the       // attributes are added to the `ckeditor5_sourceEditing` allowed tags.       if (!$editor->getImageUploadSettings()['status']) {
        // Add `sourceEditing` toolbar item if it does not already exist.         if (!in_array('sourceEditing', $settings['toolbar']['items'], TRUE)) {
          $settings['toolbar']['items'][] = '|';
          $settings['toolbar']['items'][] = 'sourceEditing';
          // @see \Drupal\ckeditor5\Plugin\CKEditor5Plugin\SourceEditing::defaultConfiguration()           $settings['plugins']['ckeditor5_sourceEditing'] = ['allowed_tags' => []];
        }
        // Update configuration.         $settings['plugins']['ckeditor5_sourceEditing']['allowed_tags'] = HTMLRestrictions::fromString(implode(' ', $settings['plugins']['ckeditor5_sourceEditing']['allowed_tags']))
          ->merge(HTMLRestrictions::fromString('<img data-entity-uuid data-entity-type>'))
          ->toCKEditor5ElementsArray();
      }

    ]);
    $editor->save();
    $this->resetAll();
    $this->drupalGet($url);
    $this->assertNotEmpty($this->cssSelect('input[type=text][name="attributes[src]"]'), 'Image uploads disabled: input[type=text][name="attributes[src]"] is present.');
    $this->assertEmpty($this->cssSelect('input[type=file]'), 'Image uploads disabled: input[type=file] is absent.');
    $session->statusCodeEquals(200);

    // With image upload settings, expect a 200, and now there should be an     // input[type=file].     $editor->setImageUploadSettings(['status' => TRUE] + $editor->getImageUploadSettings())
      ->save();
    $this->resetAll();
    $this->drupalGet($url);
    $this->assertEmpty($this->cssSelect('input[type=text][name="attributes[src]"]'), 'Image uploads enabled: input[type=text][name="attributes[src]"] is absent.');
    $this->assertNotEmpty($this->cssSelect('input[type=file]'), 'Image uploads enabled: input[type=file] is present.');
    $session->statusCodeEquals(200);
  }

}
        'editor' => 'ckeditor5',
      ]);
    $editor->setEditor('ckeditor5');

    $source_editing_additions = HTMLRestrictions::emptySet();
    // Compute the appropriate settings based on the CKEditor 4 configuration     // if it exists.     $old_editor = $editor->id() ? Editor::load($editor->id()) : NULL;
    $old_editor_restrictions = $old_editor ? HTMLRestrictions::fromTextFormat($old_editor->getFilterFormat()) : HTMLRestrictions::emptySet();
    // @todo Remove in https://www.drupal.org/project/drupal/issues/3245351     if ($old_editor) {
      $editor->setImageUploadSettings($old_editor->getImageUploadSettings());
    }
    if ($old_editor && $old_editor->getEditor() === 'ckeditor') {
      [$upgraded_settings$messages] = $this->createSettingsFromCKEditor4($old_editor->getSettings(), HTMLRestrictions::fromTextFormat($old_editor->getFilterFormat()));
      $editor->setSettings($upgraded_settings);
      // *Before* determining which elements are still needed for this text       // format, ensure that all already enabled plugins that are configurable       // have valid settings.       // For all already enabled plugins, find the ones that are configurable,       // and add their default settings. For enabled plugins with element       // subsets, compute the appropriate settings to achieve the subset that       // matches the original text format restrictions.
$toolbar_item_label = $definition->getToolbarItems()[$toolbar_item]['label'];
    $text_editor = $this->createTextEditorObjectFromContext();

    $conditions = $definition->getConditions();
    foreach ($conditions as $condition_type => $required_value) {
      switch ($condition_type) {
        case 'toolbarItem':
          // Nothing to validate.           break;

        case 'imageUploadStatus':
          $image_upload_settings = $text_editor->getImageUploadSettings();
          if (!isset($image_upload_settings['status']) || (bool) $image_upload_settings['status'] !== TRUE) {
            $this->context->buildViolation($constraint->imageUploadStatusRequiredMessage)
              ->setParameter('%toolbar_item', (string) $toolbar_item_label)
              ->setInvalidValue($toolbar_item)
              ->addViolation();
          }
          break;

        case 'filter':
          $filters = $text_editor->getFilterFormat()->filters();
          if (!$filters->has($required_value) || !$filters->get($required_value)->status) {
            

class Image extends CKEditor5PluginDefault implements CKEditor5PluginConfigurableInterface {

  use CKEditor5PluginConfigurableTrait;
  use DynamicPluginConfigWithCsrfTokenUrlTrait;

  /** * {@inheritdoc} */
  public function getDynamicPluginConfig(array $static_plugin_config, EditorInterface $editor): array {
    $config = $static_plugin_config;
    if ($editor->getImageUploadSettings()['status'] === TRUE) {
      $config += [
        'drupalImageUpload' => [
          'uploadUrl' => self::getUrlWithReplacedCsrfTokenPlaceholder(
            Url::fromRoute('ckeditor5.upload_image')
              ->setRouteParameter('editor', $editor->getFilterFormat()->id())
          ),
          'withCredentials' => TRUE,
          'headers' => ['Accept' => 'application/json', 'text/javascript'],
        ],
      ];
    }
    
else {
      // Retrieve the image element's attributes from form state.       $image_element = $form_state->get('image_element') ?: [];
    }

    $form['#tree'] = TRUE;
    $form['#attached']['library'][] = 'editor/drupal.editor.dialog';
    $form['#prefix'] = '<div id="editor-image-dialog-form">';
    $form['#suffix'] = '</div>';

    // Construct strings to use in the upload validators.     $image_upload = $editor->getImageUploadSettings();
    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;
    }
    $max_filesize = min(Bytes::toNumber($image_upload['max_size']), Environment::getUploadMaxSize());
    $existing_file = isset($image_element['data-entity-uuid']) ? \Drupal::service('entity.repository')->loadEntityByUuid('file', $image_element['data-entity-uuid']) : NULL;
    $fid = $existing_file ? $existing_file->id() : NULL;

    $form['fid'] = [
      
    $updated_text_editor->save();

    // We should now have the expected data in the Editor config entity.     $this->assertSame('ckeditor5', $updated_text_editor->getEditor());
    $this->assertSame($expected_ckeditor5_settings$updated_text_editor->getSettings());

    // If this text format already had a text editor, ensure that the settings     // do not match the original settings, but the image upload settings should     // not have been changed.     if ($text_editor !== NULL) {
      $this->assertNotSame($text_editor->getSettings()$updated_text_editor->getSettings());
      $this->assertSame($text_editor->getImageUploadSettings()$updated_text_editor->getImageUploadSettings());
    }

    // The resulting Editor config entity should be valid.     $violations = $this->validatePairToViolationsArray($updated_text_editor$text_format, FALSE);
    // At this point, the fundamental compatibility errors do not matter, they     // have been checked above; whatever remains is expected.     if (isset($violations[''])) {
      unset($violations['']);
    }
    $this->assertSame([]$violations);

    
/** * Sets the maximum dimensions and saves the configuration. * * @param string|int $width * The width of the image. * @param string|int $height * The height of the image. */
  protected function setMaxDimensions($width$height) {
    $editor = Editor::load('basic_html');
    $image_upload_settings = $editor->getImageUploadSettings();
    $image_upload_settings['max_dimensions']['width'] = $width;
    $image_upload_settings['max_dimensions']['height'] = $height;
    $editor->setImageUploadSettings($image_upload_settings);
    $editor->save();
  }

  /** * Uploads an image via the editor dialog. * * @param string $uri * The URI of the image. * * @return array * An array containing the uploaded image's width and height. */
'max_size' => '',
      'max_dimensions' => [
        'width' => 0,
        'height' => 0,
      ],
    ]);

    // Ensure that images cannot be uploaded when image upload is disabled.     $response = $this->uploadRequest($url$test_image, 'test.jpg');
    $this->assertSame(403, $response->getStatusCode());

    $editor->setImageUploadSettings(['status' => TRUE] + $editor->getImageUploadSettings())
      ->save();
    $response = $this->uploadRequest($url$test_image, 'test.jpg');
    $this->assertSame(201, $response->getStatusCode());

    // Ensure lock failures are reported correctly.     $d = 'public://inline-images/test.jpg';
    $f = $this->container->get('file_system')->getDestinationFilename($d, FileSystemInterface::EXISTS_RENAME);
    $this->container->get('lock')
      ->acquire('file:ckeditor5:' . Crypt::hashBase64($f));
    $response = $this->uploadRequest($url$test_image, 'test.jpg');
    $this->assertSame(503, $response->getStatusCode());
    
Home | Imprint | This part of the site doesn't use cookies.