CKEditor.php 14.2 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\ckeditor\Plugin\Editor\CKEditor.
6 7
 */

8
namespace Drupal\ckeditor\Plugin\Editor;
9

10 11
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
12
use Drupal\ckeditor\CKEditorPluginManager;
13
use Drupal\Core\Language\Language;
14
use Drupal\Core\Language\LanguageManager;
15
use Drupal\Core\Render\Element;
16
use Drupal\editor\Plugin\EditorBase;
17
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
18
use Drupal\editor\Entity\Editor as EditorEntity;
19
use Symfony\Component\DependencyInjection\ContainerInterface;
20 21 22 23

/**
 * Defines a CKEditor-based text editor for Drupal.
 *
24
 * @Editor(
25 26
 *   id = "ckeditor",
 *   label = @Translation("CKEditor"),
27
 *   supports_content_filtering = TRUE,
28 29
 *   supports_inline_editing = TRUE,
 *   is_xss_safe = FALSE
30 31
 * )
 */
32
class CKEditor extends EditorBase implements ContainerFactoryPluginInterface {
33

34 35 36 37 38 39 40 41 42 43 44 45 46 47
  /**
   * The module handler to invoke hooks on.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The language manager.
   *
   * @var \Drupal\Core\Language\LanguageManager
   */
  protected $languageManager;

48
  /**
49 50 51 52 53 54 55 56 57 58 59 60 61
   * The CKEditor plugin manager.
   *
   * @var \Drupal\ckeditor\CKEditorPluginManager
   */
  protected $ckeditorPluginManager;

  /**
   * Constructs a Drupal\Component\Plugin\PluginBase object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
62
   * @param mixed $plugin_definition
63 64 65
   *   The plugin implementation definition.
   * @param \Drupal\ckeditor\CKEditorPluginManager $ckeditor_plugin_manager
   *   The CKEditor plugin manager.
66 67 68 69
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler to invoke hooks on.
   * @param \Drupal\Core\Language\LanguageManager $language_manager
   *   The language manager.
70
   */
71
  public function __construct(array $configuration, $plugin_id, $plugin_definition, CKEditorPluginManager $ckeditor_plugin_manager, ModuleHandlerInterface $module_handler, LanguageManager $language_manager) {
72 73
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->ckeditorPluginManager = $ckeditor_plugin_manager;
74 75
    $this->moduleHandler = $module_handler;
    $this->languageManager = $language_manager;
76 77 78 79 80
  }

  /**
   * {@inheritdoc}
   */
81
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
82 83 84 85 86 87 88 89
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('plugin.manager.ckeditor.plugin'),
      $container->get('module_handler'),
      $container->get('language_manager')
    );
90 91 92 93
  }

  /**
   * {@inheritdoc}
94 95 96 97
   */
  public function getDefaultSettings() {
    return array(
      'toolbar' => array(
98 99
        'rows' => array(
          // Button groups.
100
          array(
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
            array(
              'name' => t('Formatting'),
              'items' => array('Bold', 'Italic',),
            ),
            array(
              'name' => t('Links'),
              'items' => array('DrupalLink', 'DrupalUnlink',),
            ),
            array(
              'name' => t('Lists'),
              'items' => array('BulletedList', 'NumberedList',),
            ),
            array(
              'name' => t('Media'),
              'items' => array('Blockquote', 'DrupalImage',),
            ),
            array(
              'name' => t('Tools'),
              'items' => array('Source',),
            ),
121 122 123 124 125 126 127 128
          ),
        ),
      ),
      'plugins' => array(),
    );
  }

  /**
129
   * {@inheritdoc}
130
   */
131
  public function settingsForm(array $form, array &$form_state, EditorEntity $editor) {
132 133
    $settings = $editor->getSettings();

134 135 136
    $ckeditor_settings_toolbar = array(
      '#theme' => 'ckeditor_settings_toolbar',
      '#editor' => $editor,
137
      '#plugins' => $this->ckeditorPluginManager->getButtons(),
138
    );
139 140 141
    $form['toolbar'] = array(
      '#type' => 'container',
      '#attached' => array(
142
        'library' => array('ckeditor/drupal.ckeditor.admin'),
143 144 145 146
        'js' => array(
          array(
            'type' => 'setting',
            'data' => array('ckeditor' => array(
147
              'toolbarAdmin' => drupal_render($ckeditor_settings_toolbar),
148 149 150 151 152 153
            )),
          )
        ),
      ),
      '#attributes' => array('class' => array('ckeditor-toolbar-configuration')),
    );
154 155

    $form['toolbar']['button_groups'] = array(
156 157
      '#type' => 'textarea',
      '#title' => t('Toolbar buttons'),
158
      '#default_value' => json_encode($settings['toolbar']['rows']),
159 160 161 162 163 164
      '#attributes' => array('class' => array('ckeditor-toolbar-textarea')),
    );

    // CKEditor plugin settings, if any.
    $form['plugin_settings'] = array(
      '#type' => 'vertical_tabs',
165
      '#title' => t('CKEditor plugin settings'),
166 167 168
      '#attributes' => array(
        'id' => 'ckeditor-plugin-settings',
      ),
169
    );
170
    $this->ckeditorPluginManager->injectPluginSettingsForm($form, $form_state, $editor);
171
    if (count(Element::children($form['plugins'])) === 0) {
172 173 174 175
      unset($form['plugins']);
      unset($form['plugin_settings']);
    }

176 177 178 179 180 181
    // Hidden CKEditor instance. We need a hidden CKEditor instance with all
    // plugins enabled, so we can retrieve CKEditor's per-feature metadata (on
    // which tags, attributes, styles and classes are enabled). This metadata is
    // necessary for certain filters' (e.g. the html_filter filter) settings to
    // be updated accordingly.
    // Get a list of all external plugins and their corresponding files.
182
    $plugins = array_keys($this->ckeditorPluginManager->getDefinitions());
183 184
    $all_external_plugins = array();
    foreach ($plugins as $plugin_id) {
185
      $plugin = $this->ckeditorPluginManager->createInstance($plugin_id);
186 187 188 189 190
      if (!$plugin->isInternal()) {
        $all_external_plugins[$plugin_id] = $plugin->getFile();
      }
    }
    // Get a list of all buttons that are provided by all plugins.
191
    $all_buttons = array_reduce($this->ckeditorPluginManager->getButtons(), function($result, $item) {
192 193 194 195 196
      return array_merge($result, array_keys($item));
    }, array());
    // Build a fake Editor object, which we'll use to generate JavaScript
    // settings for this fake Editor instance.
    $fake_editor = entity_create('editor', array(
197
      'format' => $editor->id(),
198 199
      'editor' => 'ckeditor',
      'settings' => array(
200 201 202 203 204 205 206 207 208 209 210
        // Single toolbar row, single button group, all existing buttons.
        'toolbar' => array(
         'rows' => array(
           0 => array(
             0 => array(
               'name' => 'All existing buttons',
               'items' => $all_buttons,
             )
           )
         ),
        ),
211
        'plugins' => $settings['plugins'],
212 213
      ),
    ));
214 215 216 217
    $config = $this->getJSSettings($fake_editor);
    // Remove the ACF configuration that is generated based on filter settings,
    // because otherwise we cannot retrieve per-feature metadata.
    unset($config['allowedContent']);
218 219 220 221 222 223 224
    $form['hidden_ckeditor'] = array(
      '#markup' => '<div id="ckeditor-hidden" class="element-hidden"></div>',
      '#attached' => array(
        'js' => array(
          array(
            'type' => 'setting',
            'data' => array('ckeditor' => array(
225
              'hiddenCKEditorConfig' => $config,
226 227 228 229 230 231
            )),
          ),
        ),
      ),
    );

232 233 234 235
    return $form;
  }

  /**
236
   * {@inheritdoc}
237 238 239 240 241 242 243
   */
  public function settingsFormSubmit(array $form, array &$form_state) {
    // Modify the toolbar settings by reference. The values in
    // $form_state['values']['editor']['settings'] will be saved directly by
    // editor_form_filter_admin_format_submit().
    $toolbar_settings = &$form_state['values']['editor']['settings']['toolbar'];

244 245 246 247
    // The rows key is not built into the form structure, so decode the button
    // groups data into this new key and remove the button_groups key.
    $toolbar_settings['rows'] = json_decode($toolbar_settings['button_groups'], TRUE);
    unset($toolbar_settings['button_groups']);
248 249 250 251 252 253 254 255

    // Remove the plugin settings' vertical tabs state; no need to save that.
    if (isset($form_state['values']['editor']['settings']['plugins'])) {
      unset($form_state['values']['editor']['settings']['plugin_settings']);
    }
  }

  /**
256
   * {@inheritdoc}
257
   */
258
  public function getJSSettings(EditorEntity $editor) {
259 260 261
    $settings = array();

    // Get the settings for all enabled plugins, even the internal ones.
262
    $enabled_plugins = array_keys($this->ckeditorPluginManager->getEnabledPluginFiles($editor, TRUE));
263
    foreach ($enabled_plugins as $plugin_id) {
264
      $plugin = $this->ckeditorPluginManager->createInstance($plugin_id);
265 266 267
      $settings += $plugin->getConfig($editor);
    }

268 269 270 271 272
    // Fall back on English if no matching language code was found.
    $display_langcode = 'en';

    // Map the interface language code to a CKEditor translation.
    $ckeditor_langcodes = $this->getLangcodes();
273
    $language_interface = $this->languageManager->getCurrentLanguage();
274 275 276 277
    if (isset($ckeditor_langcodes[$language_interface->id])) {
      $display_langcode = $ckeditor_langcodes[$language_interface->id];
    }

278
    // Next, set the most fundamental CKEditor settings.
279
    $external_plugin_files = $this->ckeditorPluginManager->getEnabledPluginFiles($editor);
280 281 282
    $settings += array(
      'toolbar' => $this->buildToolbarJSSetting($editor),
      'contentsCss' => $this->buildContentsCssJSSetting($editor),
283
      'extraPlugins' => implode(',', array_keys($external_plugin_files)),
284
      'language' => $display_langcode,
285 286 287 288 289 290
      // Configure CKEditor to not load styles.js. The StylesCombo plugin will
      // set stylesSet according to the user's settings, if the "Styles" button
      // is enabled. We cannot get rid of this until CKEditor will stop loading
      // styles.js by default.
      // See http://dev.ckeditor.com/ticket/9992#comment:9.
      'stylesSet' => FALSE,
291 292 293 294
    );

    // Finally, set Drupal-specific CKEditor settings.
    $settings += array(
295
      'drupalExternalPlugins' => array_map('file_create_url', $external_plugin_files),
296 297
    );

298 299
    // Parse all CKEditor plugin JavaScript files for translations.
    if ($this->moduleHandler->moduleExists('locale')) {
300
      locale_js_translate(array_values($external_plugin_files));
301 302
    }

303 304
    ksort($settings);

305 306 307
    return $settings;
  }

308 309 310 311 312 313 314 315 316 317 318
  /**
   * Returns a list of language codes supported by CKEditor.
   *
   * @return array
   *   An associative array keyed by language codes.
   */
  public function getLangcodes() {
    // Cache the file system based language list calculation because this would
    // be expensive to calculate all the time. The cache is cleared on core
    // upgrades which is the only situation the CKEditor file listing should
    // change.
319
    $langcode_cache = \Drupal::cache()->get('ckeditor.langcodes');
320 321 322 323 324 325
    if (!empty($langcode_cache)) {
      $langcodes = $langcode_cache->data;
    }
    if (empty($langcodes)) {
      $langcodes = array();
      // Collect languages included with CKEditor based on file listing.
326 327 328
      $ckeditor_languages = new \GlobIterator(DRUPAL_ROOT . '/core/assets/vendor/ckeditor/lang/*.js');
      foreach ($ckeditor_languages as $language_file) {
        $langcode = $language_file->getBasename('.js');
329 330
        $langcodes[$langcode] = $langcode;
      }
331
      \Drupal::cache()->set('ckeditor.langcodes', $langcodes);
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
    }

    // Get language mapping if available to map to Drupal language codes.
    // This is configurable in the user interface and not expensive to get, so
    // we don't include it in the cached language list.
    $language_mappings = $this->moduleHandler->moduleExists('language') ? language_get_browser_drupal_langcode_mappings() : array();
    foreach ($langcodes as $langcode) {
      // If this language code is available in a Drupal mapping, use that to
      // compute a possibility for matching from the Drupal langcode to the
      // CKEditor langcode.
      // e.g. CKEditor uses the langcode 'no' for Norwegian, Drupal uses 'nb'.
      // This would then remove the 'no' => 'no' mapping and replace it with
      // 'nb' => 'no'. Now Drupal knows which CKEditor translation to load.
      if (isset($language_mappings[$langcode]) && !isset($langcodes[$language_mappings[$langcode]])) {
        $langcodes[$language_mappings[$langcode]] = $langcode;
        unset($langcodes[$langcode]);
      }
    }

    return $langcodes;
  }

354
  /**
355
   * {@inheritdoc}
356
   */
357
  public function getLibraries(EditorEntity $editor) {
358
    $libraries = array(
359
      'ckeditor/drupal.ckeditor',
360
    );
361 362

    // Get the required libraries for any enabled plugins.
363
    $enabled_plugins = array_keys($this->ckeditorPluginManager->getEnabledPluginFiles($editor));
364 365
    foreach ($enabled_plugins as $plugin_id) {
      $plugin = $this->ckeditorPluginManager->createInstance($plugin_id);
366
      $additional_libraries = array_diff($plugin->getLibraries($editor), $libraries);
367 368 369 370
      $libraries = array_merge($libraries, $additional_libraries);
    }

    return $libraries;
371 372 373 374 375 376 377
  }

  /**
   * Builds the "toolbar" configuration part of the CKEditor JS settings.
   *
   * @see getJSSettings()
   *
378
   * @param \Drupal\editor\Entity\Editor $editor
379 380 381 382
   *   A configured text editor object.
   * @return array
   *   An array containing the "toolbar" configuration.
   */
383
  public function buildToolbarJSSetting(EditorEntity $editor) {
384
    $toolbar = array();
385 386 387

    $settings = $editor->getSettings();
    foreach ($settings['toolbar']['rows'] as $row) {
388 389
      foreach ($row as $group) {
        $toolbar[] = $group;
390 391 392 393 394 395 396 397 398 399 400
      }
      $toolbar[] = '/';
    }
    return $toolbar;
  }

  /**
   * Builds the "contentsCss" configuration part of the CKEditor JS settings.
   *
   * @see getJSSettings()
   *
401
   * @param \Drupal\editor\Entity\Editor $editor
402 403 404 405
   *   A configured text editor object.
   * @return array
   *   An array containing the "contentsCss" configuration.
   */
406
  public function buildContentsCssJSSetting(EditorEntity $editor) {
407 408
    $css = array(
      drupal_get_path('module', 'ckeditor') . '/css/ckeditor-iframe.css',
409
      drupal_get_path('module', 'system') . '/css/system.module.css',
410
    );
411
    $this->moduleHandler->alter('ckeditor_css', $css, $editor);
412
    $css = array_merge($css, _ckeditor_theme_css());
413 414 415 416 417 418
    $css = array_map('file_create_url', $css);

    return array_values($css);
  }

}