/**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state, FilterFormat $filter_format = NULL)
 {
     // Add AJAX support.
     $form['#prefix'] = '<div id="video-embed-dialog-form">';
     $form['#suffix'] = '</div>';
     // Ensure relevant dialog libraries are attached.
     $form['#attached']['library'][] = 'editor/drupal.editor.dialog';
     // Simple URL field and submit button for video URL.
     $form['video_url'] = ['#type' => 'textfield', '#title' => $this->t('Video URL'), '#required' => TRUE, '#default_value' => $this->getUserInput($form_state, 'video_url')];
     // If no settings are found, use the defaults configured in the filter
     // formats interface.
     $settings = $this->getUserInput($form_state, 'settings');
     if (empty($settings) && ($editor = Editor::load($filter_format->id()))) {
         $editor_settings = $editor->getSettings();
         $plugin_settings = NestedArray::getValue($editor_settings, ['plugins', 'video_embed', 'defaults', 'children']);
         $settings = $plugin_settings ? $plugin_settings : [];
     }
     // Create a settings form from the existing video formatter.
     $form['settings'] = Video::mockInstance($settings)->settingsForm([], new FormState());
     $form['settings']['#type'] = 'fieldset';
     $form['settings']['#title'] = $this->t('Settings');
     $form['actions'] = ['#type' => 'actions'];
     $form['actions']['save_modal'] = ['#type' => 'submit', '#value' => $this->t('Save'), '#submit' => [], '#ajax' => ['callback' => '::ajaxSubmit', 'event' => 'click', 'wrapper' => 'video-embed-dialog-form']];
     return $form;
 }
Example #2
0
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->filter = FilterFormat::create(['format' => 'test_format', 'name' => $this->randomMachineName()]);
     $this->filter->setFilterConfig('video_embed_wysiwyg', ['status' => 1]);
     $this->filter->save();
 }
Example #3
0
 protected function setUp()
 {
     // Mock text format configuration entity object.
     $this->format = $this->getMockBuilder('\\Drupal\\filter\\Entity\\FilterFormat')->disableOriginalConstructor()->getMock();
     $this->format->expects($this->any())->method('getFilterTypes')->will($this->returnValue(array(FilterInterface::TYPE_HTML_RESTRICTOR)));
     $restrictions = array('allowed' => array('p' => TRUE, 'a' => TRUE, '*' => array('style' => FALSE, 'on*' => FALSE)));
     $this->format->expects($this->any())->method('getHtmlRestrictions')->will($this->returnValue($restrictions));
 }
Example #4
0
 /**
  * Test the format tags settings.
  *
  * @dataProvider formatTagsSettingsTestCases
  */
 public function testFormatTagsSettings($filter_plugins, $expected_format_tags)
 {
     foreach ($filter_plugins as $filter_plugin_id => $filter_plugin_settings) {
         $this->format->setFilterConfig($filter_plugin_id, $filter_plugin_settings);
     }
     $this->format->save();
     $internal_plugin = $this->ckeditorPluginManager->createInstance('internal', []);
     $plugin_config = $internal_plugin->getConfig($this->editor);
     $this->assertEquals($expected_format_tags, explode(';', $plugin_config['format_tags']));
 }
 /**
  * Sets up mocks for buildForm() calls.
  *
  * @param object $asset
  *   An asset to load from the entity type manager.
  */
 private function setUpBuildForm($asset = NULL)
 {
     $this->mockFilter->expects($this->exactly(2))->method('id')->willReturn(self::MOCK_FILTER_ID);
     $filter_align = new \stdClass();
     $filter_align->status = 1;
     $this->mockFilter->expects($this->once())->method('filters')->with('filter_align')->willReturn($filter_align);
     $catalog_id = 'test_catalog';
     $editor_settings['plugins']['embridgeimage']['embridge_image_upload'] = ['max_size' => '2 MB', 'library_id' => 101, 'catalog_id' => $catalog_id, 'directory' => 'test-directory'];
     $mock_editor = $this->getMockBuilder(Editor::class)->disableOriginalConstructor()->getMock();
     $mock_editor->expects($this->once())->method('getSettings')->willReturn($editor_settings);
     $mock_editor_storage = $this->getMockBuilder(EntityStorageInterface::class)->disableOriginalConstructor()->getMock();
     $mock_editor_storage->expects($this->once())->method('load')->with(self::MOCK_FILTER_ID)->willReturn($mock_editor);
     $mock_catalog = $this->getMockBuilder(EmbridgeCatalog::class)->disableOriginalConstructor()->getMock();
     $mock_catalog->expects($this->any())->method('getApplicationId')->willReturn('test_application');
     $mock_catalog->expects($this->once())->method('getConversionsArray')->willReturn(['thumb', 'medium', 'large']);
     $mock_catalog_storage = $this->getMockBuilder(EntityStorageInterface::class)->disableOriginalConstructor()->getMock();
     $mock_catalog_storage->expects($this->once())->method('load')->with($catalog_id)->willReturn($mock_catalog);
     $map = [['editor', $mock_editor_storage], ['embridge_catalog', $mock_catalog_storage]];
     if ($asset) {
         $mock_asset_storage = $this->getMockBuilder(EntityStorageInterface::class)->disableOriginalConstructor()->getMock();
         $mock_asset_storage->expects($this->once())->method('load')->willReturn($asset);
         $map[] = ['embridge_asset_entity', $mock_asset_storage];
     }
     $this->entityTypeManager->expects($this->exactly(count($map)))->method('getStorage')->will($this->returnValueMap($map));
 }
    /**
     * Ensure comment form works with history and big_pipe modules.
     *
     * @see https://www.drupal.org/node/2698811
     */
    public function testCommentForm_2698811()
    {
        $this->assertTrue($this->container->get('module_installer')->install(['comment', 'history', 'ckeditor'], TRUE), 'Installed modules.');
        // Ensure an `article` node type exists.
        $this->createContentType(['type' => 'article']);
        $this->addDefaultCommentField('node', 'article');
        // Enable CKEditor.
        $format = $this->randomMachineName();
        FilterFormat::create(['format' => $format, 'name' => $this->randomString(), 'weight' => 1, 'filters' => []])->save();
        $settings['toolbar']['rows'] = [[['name' => 'Links', 'items' => ['DrupalLink', 'DrupalUnlink']]]];
        $editor = Editor::create(['format' => $format, 'editor' => 'ckeditor']);
        $editor->setSettings($settings);
        $editor->save();
        $admin_user = $this->drupalCreateUser(['access comments', 'post comments', 'use text format ' . $format]);
        $this->drupalLogin($admin_user);
        $node = $this->createNode(['type' => 'article', 'comment' => CommentItemInterface::OPEN]);
        // Create some comments.
        foreach (range(1, 5) as $i) {
            $comment = Comment::create(['status' => CommentInterface::PUBLISHED, 'field_name' => 'comment', 'entity_type' => 'node', 'entity_id' => $node->id()]);
            $comment->save();
        }
        $this->drupalGet($node->toUrl()->toString());
        // Confirm that CKEditor loaded.
        $javascript = <<<JS
    (function(){
      return Object.keys(CKEDITOR.instances).length > 0;
    }());
JS;
        $this->assertJsCondition($javascript);
    }
Example #7
0
 protected function setUp()
 {
     parent::setUp();
     // Let there be T-rex.
     \Drupal::state()->set('editor_test_give_me_a_trex_thanks', TRUE);
     \Drupal::service('plugin.manager.editor')->clearCachedDefinitions();
     // Add text formats.
     $filtered_html_format = FilterFormat::create(array('format' => 'filtered_html', 'name' => 'Filtered HTML', 'weight' => 0, 'filters' => array()));
     $filtered_html_format->save();
     $full_html_format = FilterFormat::create(array('format' => 'full_html', 'name' => 'Full HTML', 'weight' => 1, 'filters' => array()));
     $full_html_format->save();
     // Create article node type.
     $this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article'));
     // Create page node type, but remove the body.
     $this->drupalCreateContentType(array('type' => 'page', 'name' => 'Page'));
     $body = FieldConfig::loadByName('node', 'page', 'body');
     $body->delete();
     // Create a formatted text field, which uses an <input type="text">.
     FieldStorageConfig::create(array('field_name' => 'field_text', 'entity_type' => 'node', 'type' => 'text'))->save();
     FieldConfig::create(array('field_name' => 'field_text', 'entity_type' => 'node', 'label' => 'Textfield', 'bundle' => 'page'))->save();
     entity_get_form_display('node', 'page', 'default')->setComponent('field_text')->save();
     // Create 3 users, each with access to different text formats.
     $this->untrustedUser = $this->drupalCreateUser(array('create article content', 'edit any article content'));
     $this->normalUser = $this->drupalCreateUser(array('create article content', 'edit any article content', 'use text format filtered_html'));
     $this->privilegedUser = $this->drupalCreateUser(array('create article content', 'edit any article content', 'create page content', 'edit any page content', 'use text format filtered_html', 'use text format full_html'));
 }
 /**
  * Tests the Drupal 6 filter format to Drupal 8 migration.
  */
 public function testFilterFormat()
 {
     $filter_format = FilterFormat::load('filtered_html');
     // Check filter status.
     $filters = $filter_format->get('filters');
     $this->assertTrue($filters['filter_autop']['status']);
     $this->assertTrue($filters['filter_url']['status']);
     $this->assertTrue($filters['filter_htmlcorrector']['status']);
     $this->assertTrue($filters['filter_html']['status']);
     // These should be false by default.
     $this->assertFalse(isset($filters['filter_html_escape']));
     $this->assertFalse(isset($filters['filter_caption']));
     $this->assertFalse(isset($filters['filter_html_image_secure']));
     // Check variables migrated into filter.
     $this->assertSame('<a href hreflang> <em> <strong> <cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd>', $filters['filter_html']['settings']['allowed_html']);
     $this->assertSame(TRUE, $filters['filter_html']['settings']['filter_html_help']);
     $this->assertSame(FALSE, $filters['filter_html']['settings']['filter_html_nofollow']);
     $this->assertSame(72, $filters['filter_url']['settings']['filter_url_length']);
     // Assert that the php_code format was migrated with filter_null in the
     // php_code filter's place.
     $filter_format = FilterFormat::load('php_code');
     $this->assertInstanceOf(FilterFormatInterface::class, $filter_format);
     $filters = $filter_format->get('filters');
     $this->assertArrayHasKey('filter_null', $filters);
     $this->assertArrayNotHasKey('php_code', $filters);
 }
Example #9
0
 /**
  * Pre-render callback: Renders a processed text element into #markup.
  *
  * Runs all the enabled filters on a piece of text.
  *
  * Note: Because filters can inject JavaScript or execute PHP code, security
  * is vital here. When a user supplies a text format, you should validate it
  * using $format->access() before accepting/using it. This is normally done in
  * the validation stage of the Form API. You should for example never make a
  * preview of content in a disallowed format.
  *
  * @param array $element
  *   A structured array with the following key-value pairs:
  *   - #text: containing the text to be filtered
  *   - #format: containing the machine name of the filter format to be used to
  *     filter the text. Defaults to the fallback format.
  *   - #langcode: the language code of the text to be filtered, e.g. 'en' for
  *     English. This allows filters to be language-aware so language-specific
  *     text replacement can be implemented. Defaults to an empty string.
  *   - #filter_types_to_skip: an array of filter types to skip, or an empty
  *     array (default) to skip no filter types. All of the format's filters
  *     will be applied, except for filters of the types that are marked to be
  *     skipped. FilterInterface::TYPE_HTML_RESTRICTOR is the only type that
  *     cannot be skipped.
  *
  * @return array
  *   The passed-in element with the filtered text in '#markup'.
  *
  * @ingroup sanitization
  */
 public static function preRenderText($element)
 {
     $format_id = $element['#format'];
     $filter_types_to_skip = $element['#filter_types_to_skip'];
     $text = $element['#text'];
     $langcode = $element['#langcode'];
     if (!isset($format_id)) {
         $format_id = static::configFactory()->get('filter.settings')->get('fallback_format');
     }
     /** @var \Drupal\filter\Entity\FilterFormat $format **/
     $format = FilterFormat::load($format_id);
     // If the requested text format doesn't exist or its disabled, the text
     // cannot be filtered.
     if (!$format || !$format->status()) {
         $message = !$format ? 'Missing text format: %format.' : 'Disabled text format: %format.';
         static::logger('filter')->alert($message, array('%format' => $format_id));
         $element['#markup'] = '';
         return $element;
     }
     $filter_must_be_applied = function (FilterInterface $filter) use($filter_types_to_skip) {
         $enabled = $filter->status === TRUE;
         $type = $filter->getType();
         // Prevent FilterInterface::TYPE_HTML_RESTRICTOR from being skipped.
         $filter_type_must_be_applied = $type == FilterInterface::TYPE_HTML_RESTRICTOR || !in_array($type, $filter_types_to_skip);
         return $enabled && $filter_type_must_be_applied;
     };
     // Convert all Windows and Mac newlines to a single newline, so filters only
     // need to deal with one possibility.
     $text = str_replace(array("\r\n", "\r"), "\n", $text);
     // Get a complete list of filters, ordered properly.
     /** @var \Drupal\filter\Plugin\FilterInterface[] $filters **/
     $filters = $format->filters();
     // Give filters a chance to escape HTML-like data such as code or formulas.
     foreach ($filters as $filter) {
         if ($filter_must_be_applied($filter)) {
             $text = $filter->prepare($text, $langcode);
         }
     }
     // Perform filtering.
     $metadata = BubbleableMetadata::createFromRenderArray($element);
     foreach ($filters as $filter) {
         if ($filter_must_be_applied($filter)) {
             $result = $filter->process($text, $langcode);
             $metadata = $metadata->merge($result);
             $text = $result->getProcessedText();
         }
     }
     // Filtering and sanitizing have been done in
     // \Drupal\filter\Plugin\FilterInterface. $text is not guaranteed to be
     // safe, but it has been passed through the filter system and checked with
     // a text format, so it must be printed as is. (See the note about security
     // in the method documentation above.)
     $element['#markup'] = FilteredMarkup::create($text);
     // Set the updated bubbleable rendering metadata and the text format's
     // cache tag.
     $metadata->applyTo($element);
     $element['#cache']['tags'] = Cache::mergeTags($element['#cache']['tags'], $format->getCacheTags());
     return $element;
 }
 protected function setUp()
 {
     parent::setUp();
     $this->installEntitySchema('entity_test_rev');
     // Create the necessary formats.
     $this->installConfig(array('filter'));
     FilterFormat::create(array('format' => 'no_filters', 'filters' => array()))->save();
 }
Example #11
0
 protected function setUp()
 {
     parent::setUp();
     $filtered_html_format = FilterFormat::create(array('format' => 'filtered_html', 'name' => 'Filtered HTML'));
     $filtered_html_format->save();
     $filtered_html_permission = $filtered_html_format->getPermissionName();
     user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array($filtered_html_permission));
 }
 /**
  * Additional #pre_render callback for 'text_format' elements.
  */
 function preRenderTextFormat(array $element)
 {
     // Allow modules to programmatically enforce no client-side editor by
     // setting the #editor property to FALSE.
     if (isset($element['#editor']) && !$element['#editor']) {
         return $element;
     }
     // filter_process_format() copies properties to the expanded 'value' child
     // element, including the #pre_render property. Skip this text format
     // widget, if it contains no 'format'.
     if (!isset($element['format'])) {
         return $element;
     }
     $format_ids = array_keys($element['format']['format']['#options']);
     // Early-return if no text editor is associated with any of the text formats.
     $editors = Editor::loadMultiple($format_ids);
     if (count($editors) === 0) {
         return $element;
     }
     // Use a hidden element for a single text format.
     $field_id = $element['value']['#id'];
     if (!$element['format']['format']['#access']) {
         // Use the first (and only) available text format.
         $format_id = $format_ids[0];
         $element['format']['editor'] = array('#type' => 'hidden', '#name' => $element['format']['format']['#name'], '#value' => $format_id, '#attributes' => array('class' => array('editor'), 'data-editor-for' => $field_id));
     } else {
         $element['format']['format']['#attributes']['class'][] = 'editor';
         $element['format']['format']['#attributes']['data-editor-for'] = $field_id;
     }
     // Hide the text format's filters' guidelines of those text formats that have
     // a text editor associated: they're rather useless when using a text editor.
     foreach ($editors as $format_id => $editor) {
         $element['format']['guidelines'][$format_id]['#access'] = FALSE;
     }
     // Attach Text Editor module's (this module) library.
     $element['#attached']['library'][] = 'editor/drupal.editor';
     // Attach attachments for all available editors.
     $element['#attached'] = drupal_merge_attached($element['#attached'], $this->pluginManager->getAttachments($format_ids));
     // Apply XSS filters when editing content if necessary. Some types of text
     // editors cannot guarantee that the end user won't become a victim of XSS.
     if (!empty($element['value']['#value'])) {
         $original = $element['value']['#value'];
         $format = FilterFormat::load($element['format']['format']['#value']);
         // Ensure XSS-safety for the current text format/editor.
         $filtered = editor_filter_xss($original, $format);
         if ($filtered !== FALSE) {
             $element['value']['#value'] = $filtered;
         }
         // Only when the user has access to multiple text formats, we must add data-
         // attributes for the original value and change tracking, because they are
         // only necessary when the end user can switch between text formats/editors.
         if ($element['format']['format']['#access']) {
             $element['value']['#attributes']['data-editor-value-is-changed'] = 'false';
             $element['value']['#attributes']['data-editor-value-original'] = $original;
         }
     }
     return $element;
 }
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     // Create a text format and associate this with CKEditor.
     FilterFormat::create(['format' => 'full_html', 'name' => 'Full HTML', 'weight' => 1, 'filters' => []])->save();
     Editor::create(['format' => 'full_html', 'editor' => 'ckeditor'])->save();
     // Create a new user with admin rights.
     $this->admin_user = $this->drupalCreateUser(['administer languages', 'access administration pages', 'administer site configuration', 'administer filters']);
 }
Example #14
0
 protected function setUp()
 {
     parent::setUp();
     // Create text format.
     $filtered_html_format = FilterFormat::create(array('format' => 'filtered_html', 'name' => 'Filtered HTML', 'weight' => 0, 'filters' => array()));
     $filtered_html_format->save();
     // Create admin user.
     $this->adminUser = $this->drupalCreateUser(array('administer filters'));
 }
 protected function setUp()
 {
     parent::setUp();
     // Install the Filter module.
     // Create text format, associate CKEditor.
     $filtered_html_format = FilterFormat::create(array('format' => 'filtered_html', 'name' => 'Filtered HTML', 'weight' => 0, 'filters' => array()));
     $filtered_html_format->save();
     $editor = Editor::create(['format' => 'filtered_html', 'editor' => 'ckeditor']);
     $editor->save();
 }
Example #16
0
 protected function setUp()
 {
     parent::setUp();
     // Install the Filter module.
     // Add text formats.
     $filtered_html_format = FilterFormat::create(array('format' => 'filtered_html', 'name' => 'Filtered HTML', 'weight' => 0, 'filters' => array()));
     $filtered_html_format->save();
     $full_html_format = FilterFormat::create(array('format' => 'full_html', 'name' => 'Full HTML', 'weight' => 1, 'filters' => array()));
     $full_html_format->save();
 }
Example #17
0
 /**
  * {@inheritdoc}
  */
 public function setUp()
 {
     parent::setUp();
     $basic_html_format = FilterFormat::load('basic_html');
     $restricted_html_format = FilterFormat::create(array('format' => 'restricted_html', 'name' => 'Restricted HTML'));
     $restricted_html_format->save();
     $full_html_format = FilterFormat::create(array('format' => 'full_html', 'name' => 'Full HTML'));
     $full_html_format->save();
     $this->loginAsAdmin(['access content overview', 'administer tmgmt', 'translate any entity', 'edit any translatable_node content', $basic_html_format->getPermissionName(), $restricted_html_format->getPermissionName(), $full_html_format->getPermissionName()]);
 }
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->format = strtolower($this->randomMachineName());
     $filter_format = FilterFormat::create(['format' => $this->format, 'name' => $this->randomString(), 'filters' => []]);
     $filter_format->save();
     $editor = Editor::create(['format' => $this->format, 'editor' => 'ckeditor']);
     $editor->save();
     $this->adminUser = $this->drupalCreateUser(['administer filters']);
 }
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     // Add text format.
     FilterFormat::create(['format' => 'basic_html', 'name' => 'Basic HTML', 'weight' => 0])->save();
     // Set up text editor.
     Editor::create(['format' => 'basic_html', 'editor' => 'unicorn', 'image_upload' => ['status' => TRUE, 'scheme' => 'public', 'directory' => 'inline-images', 'max_size' => '', 'max_dimensions' => ['width' => NULL, 'height' => NULL]]])->save();
     // Create admin user.
     $this->adminUser = $this->drupalCreateUser(['administer filters', 'use text format basic_html']);
     $this->drupalLogin($this->adminUser);
 }
 protected function setUp()
 {
     parent::setUp();
     // Create a text format.
     $filtered_html_format = FilterFormat::create(array('format' => 'filtered_html', 'name' => 'Filtered HTML', 'weight' => 0, 'filters' => array('filter_caption' => array('status' => 1))));
     $filtered_html_format->save();
     // Create a node type.
     $this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article'));
     // Create one node of the above node type using the above text format.
     $this->drupalCreateNode(array('type' => 'article', 'body' => array(0 => array('value' => '<p>Do you also love Drupal?</p><img src="druplicon.png" data-caption="Druplicon" />', 'format' => 'filtered_html'))));
 }
Example #21
0
 /**
  * Tests disabling the fallback text format.
  */
 public function testDisableFallbackFormat()
 {
     $this->installConfig(['filter']);
     $message = '\\LogicException with message "The fallback text format \'plain_text\' cannot be disabled." was thrown.';
     try {
         FilterFormat::load('plain_text')->disable();
         $this->fail($message);
     } catch (\LogicException $e) {
         $this->assertIdentical($e->getMessage(), "The fallback text format 'plain_text' cannot be disabled.", $message);
     }
 }
 /**
  * Tests that changes to FilterFormat::$roles do not have an effect.
  */
 function testUpdateRoles()
 {
     // Verify role permissions declared in default config.
     $format = FilterFormat::load('filter_test');
     $this->assertEqual(array_keys(filter_get_roles_by_format($format)), array(RoleInterface::ANONYMOUS_ID, RoleInterface::AUTHENTICATED_ID));
     // Attempt to change roles.
     $format->set('roles', array(RoleInterface::AUTHENTICATED_ID));
     $format->save();
     // Verify that roles have not been updated.
     $format = FilterFormat::load('filter_test');
     $this->assertEqual(array_keys(filter_get_roles_by_format($format)), array(RoleInterface::ANONYMOUS_ID, RoleInterface::AUTHENTICATED_ID));
 }
Example #23
0
 protected function setUp()
 {
     parent::setUp();
     // Create Basic page node type.
     $this->drupalCreateContentType(array('type' => 'page', 'name' => 'Basic page'));
     /** @var \Drupal\filter\Entity\FilterFormat $filtered_html_format */
     $filtered_html_format = FilterFormat::load('filtered_html');
     $filtered_html_permission = $filtered_html_format->getPermissionName();
     user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array($filtered_html_permission));
     $this->adminUser = $this->drupalCreateUser(array('administer modules', 'administer filters', 'administer site configuration'));
     $this->drupalLogin($this->adminUser);
 }
Example #24
0
 /**
  * {@inheritdoc}
  */
 function setUp()
 {
     parent::setUp();
     $this->addLanguage('de');
     $filtered_html_format = FilterFormat::create(array('format' => 'filtered_html', 'name' => 'Filtered HTML'));
     $filtered_html_format->save();
     $this->drupalCreateContentType(array('type' => 'test_bundle'));
     $this->loginAsAdmin(array('create translation jobs', 'submit translation jobs', 'create test_bundle content', $filtered_html_format->getPermissionName()));
     file_unmanaged_copy(DRUPAL_ROOT . '/core/misc/druplicon.png', 'public://example.jpg');
     $this->image = File::create(array('uri' => 'public://example.jpg'));
     $this->image->save();
 }
Example #25
0
 protected function setUp()
 {
     parent::setUp();
     // Install the Filter module.
     // Create text format, associate CKEditor.
     $filtered_html_format = FilterFormat::create(array('format' => 'filtered_html', 'name' => 'Filtered HTML', 'weight' => 0, 'filters' => array('filter_html' => array('status' => 1, 'settings' => array('allowed_html' => '<h2 id> <h3> <h4> <h5> <h6> <p> <br> <strong> <a href hreflang>')))));
     $filtered_html_format->save();
     $editor = Editor::create(['format' => 'filtered_html', 'editor' => 'ckeditor']);
     $editor->save();
     // Create "CKEditor" text editor plugin instance.
     $this->ckeditor = $this->container->get('plugin.manager.editor')->createInstance('ckeditor');
 }
Example #26
0
 /**
  * Verifies that a text format is properly stored.
  */
 function verifyTextFormat($format)
 {
     $t_args = array('%format' => $format->label());
     $default_langcode = \Drupal::languageManager()->getDefaultLanguage()->getId();
     // Verify the loaded filter has all properties.
     $filter_format = FilterFormat::load($format->id());
     $this->assertEqual($filter_format->id(), $format->id(), format_string('filter_format_load: Proper format id for text format %format.', $t_args));
     $this->assertEqual($filter_format->label(), $format->label(), format_string('filter_format_load: Proper title for text format %format.', $t_args));
     $this->assertEqual($filter_format->get('weight'), $format->get('weight'), format_string('filter_format_load: Proper weight for text format %format.', $t_args));
     // Check that the filter was created in site default language.
     $this->assertEqual($format->language()->getId(), $default_langcode, format_string('filter_format_load: Proper language code for text format %format.', $t_args));
 }
 /**
  * Tests [entity:field_name] tokens.
  */
 public function testEntityFieldTokens()
 {
     // Create a node with a value in the text field and test its token.
     $format = FilterFormat::create(['format' => 'test', 'weight' => 1, 'filters' => ['filter_html_escape' => ['status' => TRUE]]]);
     $format->save();
     $entity = Node::create(['title' => 'Test node title', 'type' => 'article', 'test_field' => ['value' => 'foo', 'format' => $format->id()]]);
     $entity->save();
     $this->assertTokens('node', ['node' => $entity], ['test_field' => Markup::create('foo')]);
     // Create a node without a value in the text field and test its token.
     $entity = Node::create(['title' => 'Test node title', 'type' => 'article']);
     $entity->save();
     $this->assertNoTokens('node', ['node' => $entity], ['test_field']);
 }
Example #28
0
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     /** @var \Drupal\filter\FilterFormatInterface $filter_test_format */
     $filter_test_format = FilterFormat::load('filter_test');
     /** @var \Drupal\filter\FilterFormatInterface $filtered_html_format */
     $filtered_html_format = FilterFormat::load('filtered_html');
     /** @var \Drupal\filter\FilterFormatInterface $full_html_format */
     $full_html_format = FilterFormat::load('full_html');
     // Create users.
     $this->adminUser = $this->drupalCreateUser(array('administer filters', $filtered_html_format->getPermissionName(), $full_html_format->getPermissionName(), $filter_test_format->getPermissionName()));
     $this->webUser = $this->drupalCreateUser(array($filtered_html_format->getPermissionName(), $filter_test_format->getPermissionName()));
 }
Example #29
0
 /**
  * Pre-render callback: Renders a processed text element into #markup.
  *
  * Runs all the enabled filters on a piece of text.
  *
  * Note: Because filters can inject JavaScript or execute PHP code, security
  * is vital here. When a user supplies a text format, you should validate it
  * using $format->access() before accepting/using it. This is normally done in
  * the validation stage of the Form API. You should for example never make a
  * preview of content in a disallowed format.
  *
  * @param array $element
  *   A structured array with the following key-value pairs:
  *   - #text: containing the text to be filtered
  *   - #format: containing the machine name of the filter format to be used to
  *     filter the text. Defaults to the fallback format.
  *   - #langcode: the language code of the text to be filtered, e.g. 'en' for
  *     English. This allows filters to be language-aware so language-specific
  *     text replacement can be implemented. Defaults to an empty string.
  *   - #filter_types_to_skip: an array of filter types to skip, or an empty
  *     array (default) to skip no filter types. All of the format's filters
  *     will be applied, except for filters of the types that are marked to be
  *     skipped. FilterInterface::TYPE_HTML_RESTRICTOR is the only type that
  *     cannot be skipped.
  *
  * @return array
  *   The passed-in element with the filtered text in '#markup'.
  *
  * @ingroup sanitization
  */
 public static function preRenderText($element)
 {
     $format_id = $element['#format'];
     $filter_types_to_skip = $element['#filter_types_to_skip'];
     $text = $element['#text'];
     $langcode = $element['#langcode'];
     if (!isset($format_id)) {
         $format_id = static::configFactory()->get('filter.settings')->get('fallback_format');
     }
     // If the requested text format does not exist, the text cannot be filtered.
     /** @var \Drupal\filter\Entity\FilterFormat $format **/
     if (!($format = FilterFormat::load($format_id))) {
         static::logger('filter')->alert('Missing text format: %format.', array('%format' => $format_id));
         $element['#markup'] = '';
         return $element;
     }
     $filter_must_be_applied = function (FilterInterface $filter) use($filter_types_to_skip) {
         $enabled = $filter->status === TRUE;
         $type = $filter->getType();
         // Prevent FilterInterface::TYPE_HTML_RESTRICTOR from being skipped.
         $filter_type_must_be_applied = $type == FilterInterface::TYPE_HTML_RESTRICTOR || !in_array($type, $filter_types_to_skip);
         return $enabled && $filter_type_must_be_applied;
     };
     // Convert all Windows and Mac newlines to a single newline, so filters only
     // need to deal with one possibility.
     $text = str_replace(array("\r\n", "\r"), "\n", $text);
     // Get a complete list of filters, ordered properly.
     /** @var \Drupal\filter\Plugin\FilterInterface[] $filters **/
     $filters = $format->filters();
     // Give filters a chance to escape HTML-like data such as code or formulas.
     foreach ($filters as $filter) {
         if ($filter_must_be_applied($filter)) {
             $text = $filter->prepare($text, $langcode);
         }
     }
     // Perform filtering.
     $metadata = BubbleableMetadata::createFromRenderArray($element);
     foreach ($filters as $filter) {
         if ($filter_must_be_applied($filter)) {
             $result = $filter->process($text, $langcode);
             $metadata = $metadata->merge($result);
             $text = $result->getProcessedText();
         }
     }
     // Filtering done, store in #markup, set the updated bubbleable rendering
     // metadata, and set the text format's cache tag.
     $element['#markup'] = $text;
     $metadata->applyTo($element);
     $element['#cache']['tags'] = Cache::mergeTags($element['#cache']['tags'], $format->getCacheTags());
     return $element;
 }
Example #30
0
 /**
  * {@inheritdoc}
  */
 function setUp()
 {
     parent::setUp();
     $filtered_html_format = FilterFormat::create(array('format' => 'filtered_html', 'name' => 'Filtered HTML'));
     $filtered_html_format->save();
     $this->addLanguage('de');
     $this->addLanguage('es');
     $this->addLanguage('el');
     // Login as translator only with limited permissions to run these tests.
     $this->loginAsTranslator(array('access administration pages', 'create translation jobs', 'submit translation jobs', $filtered_html_format->getPermissionName()), TRUE);
     $this->drupalPlaceBlock('system_breadcrumb_block');
     $this->createNodeType('page', 'Page', TRUE);
     $this->createNodeType('article', 'Article', TRUE);
 }