/**
  * 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);
 }
Exemplo n.º 2
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;
 }
Exemplo n.º 3
0
 /**
  * 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;
 }
Exemplo n.º 4
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()]);
 }
Exemplo n.º 5
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);
     }
 }
Exemplo n.º 6
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 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));
 }
Exemplo n.º 8
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);
 }
Exemplo n.º 9
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()));
 }
Exemplo n.º 10
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;
 }
 /**
  * Tests all text field formatters.
  */
 public function testFormatters()
 {
     $formatters = array('text_default', 'text_trimmed', 'text_summary_or_trimmed');
     // Create the entity to be referenced.
     $entity = entity_create($this->entityType, array('name' => $this->randomMachineName()));
     $entity->formatted_text = array('value' => 'Hello, world!', 'format' => 'my_text_format');
     $entity->save();
     foreach ($formatters as $formatter) {
         // Verify the text field formatter's render array.
         $build = $entity->get('formatted_text')->view(array('type' => $formatter));
         drupal_render($build[0]);
         $this->assertEqual($build[0]['#markup'], "<p>Hello, world!</p>\n");
         $this->assertEqual($build[0]['#cache']['tags'], FilterFormat::load('my_text_format')->getCacheTag(), format_string('The @formatter formatter has the expected cache tags when formatting a formatted text field.', array('@formatter' => $formatter)));
     }
 }
Exemplo n.º 12
0
 /**
  * Tests system_update_8009().
  */
 public function testAllowedHtmlUpdate()
 {
     // Make sure we have the expected values before the update.
     $filters_before = ['basic_html' => '<a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <h4> <h5> <h6> <p> <br> <span> <img>', 'restricted_html' => '<a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <h4> <h5> <h6>'];
     foreach ($filters_before as $name => $before) {
         $config = FilterFormat::load($name)->toArray();
         $this->assertIdentical($before, $config['filters']['filter_html']['settings']['allowed_html']);
     }
     $this->runUpdates();
     // Make sure we have the expected values after the update.
     $filters_after = ['basic_html' => '<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h4 id> <h5 id> <h6 id> <p> <br> <span> <img src alt height width data-align data-caption>', 'restricted_html' => '<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h4 id> <h5 id> <h6 id>'];
     foreach ($filters_after as $name => $after) {
         $config = FilterFormat::load($name)->toArray();
         $this->assertIdentical($after, $config['filters']['filter_html']['settings']['allowed_html']);
     }
 }
 /**
  * Tests the Drupal 7 filter format to Drupal 8 migration.
  */
 public function testFilterFormat()
 {
     $this->assertEntity('custom_text_format', 'Custom Text format', ['filter_autop', 'filter_html']);
     $this->assertEntity('filtered_html', 'Filtered HTML', ['filter_autop', 'filter_html', 'filter_htmlcorrector', 'filter_url']);
     $this->assertEntity('full_html', 'Full HTML', ['filter_autop', 'filter_htmlcorrector', 'filter_url']);
     $this->assertEntity('plain_text', 'Plain text', ['filter_html_escape', 'filter_url', 'filter_autop']);
     // This assertion covers issue #2555089. Drupal 7 formats are identified
     // by machine names, so migrated formats should be merged into existing
     // ones.
     $this->assertNull(FilterFormat::load('plain_text1'));
     // Ensure that filter-specific settings were migrated.
     /** @var \Drupal\filter\FilterFormatInterface $format */
     $format = FilterFormat::load('filtered_html');
     $config = $format->filters('filter_html')->getConfiguration();
     $this->assertIdentical('<div> <span> <ul> <li>', $config['settings']['allowed_html']);
     $config = $format->filters('filter_url')->getConfiguration();
     $this->assertIdentical(128, $config['settings']['filter_url_length']);
 }
Exemplo n.º 14
0
 /**
  * Tests if the default text format is accessible to users.
  */
 function testDefaultTextFormats()
 {
     // Create two text formats, and two users. The first user has access to
     // both formats, but the second user only has access to the second one.
     $admin_user = $this->drupalCreateUser(array('administer filters'));
     $this->drupalLogin($admin_user);
     $formats = array();
     for ($i = 0; $i < 2; $i++) {
         $edit = array('format' => Unicode::strtolower($this->randomMachineName()), 'name' => $this->randomMachineName());
         $this->drupalPostForm('admin/config/content/formats/add', $edit, t('Save configuration'));
         $this->resetFilterCaches();
         $formats[] = FilterFormat::load($edit['format']);
     }
     list($first_format, $second_format) = $formats;
     $second_format_permission = $second_format->getPermissionName();
     $first_user = $this->drupalCreateUser(array($first_format->getPermissionName(), $second_format_permission));
     $second_user = $this->drupalCreateUser(array($second_format_permission));
     // Adjust the weights so that the first and second formats (in that order)
     // are the two lowest weighted formats available to any user.
     $edit = array();
     $edit['formats[' . $first_format->id() . '][weight]'] = -2;
     $edit['formats[' . $second_format->id() . '][weight]'] = -1;
     $this->drupalPostForm('admin/config/content/formats', $edit, t('Save'));
     $this->resetFilterCaches();
     // Check that each user's default format is the lowest weighted format that
     // the user has access to.
     $actual = filter_default_format($first_user);
     $expected = $first_format->id();
     $this->assertEqual($actual, $expected, "First user's default format {$actual} is the expected lowest weighted format {$expected} that the user has access to.");
     $actual = filter_default_format($second_user);
     $expected = $second_format->id();
     $this->assertEqual($actual, $expected, "Second user's default format {$actual} is the expected lowest weighted format {$expected} that the user has access to, and different to the first user's.");
     // Reorder the two formats, and check that both users now have the same
     // default.
     $edit = array();
     $edit['formats[' . $second_format->id() . '][weight]'] = -3;
     $this->drupalPostForm('admin/config/content/formats', $edit, t('Save'));
     $this->resetFilterCaches();
     $this->assertEqual(filter_default_format($first_user), filter_default_format($second_user), 'After the formats are reordered, both users have the same default format.');
 }
Exemplo n.º 15
0
 /**
  * Tests the Drupal 7 filter format to Drupal 8 migration.
  */
 public function testFilterFormat()
 {
     $this->assertEntity('custom_text_format', 'Custom Text format', ['filter_autop', 'filter_html']);
     $this->assertEntity('filtered_html', 'Filtered HTML', ['filter_autop', 'filter_html', 'filter_htmlcorrector', 'filter_url']);
     $this->assertEntity('full_html', 'Full HTML', ['filter_autop', 'filter_htmlcorrector', 'filter_url']);
     $this->assertEntity('plain_text', 'Plain text', ['filter_html_escape', 'filter_url', 'filter_autop']);
     // This assertion covers issue #2555089. Drupal 7 formats are identified
     // by machine names, so migrated formats should be merged into existing
     // ones.
     $this->assertNull(FilterFormat::load('plain_text1'));
     // Ensure that filter-specific settings were migrated.
     /** @var \Drupal\filter\FilterFormatInterface $format */
     $format = FilterFormat::load('filtered_html');
     $config = $format->filters('filter_html')->getConfiguration();
     $this->assertIdentical('<div> <span> <ul type> <li> <ol start type> <a href hreflang> <img src alt height width>', $config['settings']['allowed_html']);
     $config = $format->filters('filter_url')->getConfiguration();
     $this->assertIdentical(128, $config['settings']['filter_url_length']);
     // The php_code format gets migrated, but the php_code filter is changed to
     // filter_null.
     $filters = FilterFormat::load('php_code')->get('filters');
     $this->assertTrue(isset($filters['filter_null']));
 }
Exemplo n.º 16
0
 protected function setUp()
 {
     parent::setUp();
     $translator_permissions = ['translate configuration'];
     /** @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');
     $admin_permissions = array_merge($translator_permissions, ['administer languages', 'administer site configuration', 'link to any page', 'administer contact forms', 'administer filters', $filtered_html_format->getPermissionName(), $full_html_format->getPermissionName(), $filter_test_format->getPermissionName(), 'access site-wide contact form', 'access contextual links', 'administer views', 'administer account settings', 'administer themes', 'bypass node access', 'administer content types', 'translate interface']);
     // Create and log in user.
     $this->translatorUser = $this->drupalCreateUser($translator_permissions);
     $this->adminUser = $this->drupalCreateUser($admin_permissions);
     // Add languages.
     foreach ($this->langcodes as $langcode) {
         ConfigurableLanguage::createFromLangcode($langcode)->save();
     }
     $this->localeStorage = $this->container->get('locale.storage');
     $this->drupalPlaceBlock('local_tasks_block');
     $this->drupalPlaceBlock('page_title_block');
 }
Exemplo n.º 17
0
 /**
  * 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->assertIdentical('<a href hreflang> <em> <strong> <cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd>', $filters['filter_html']['settings']['allowed_html']);
     $this->assertIdentical(TRUE, $filters['filter_html']['settings']['filter_html_help']);
     $this->assertIdentical(FALSE, $filters['filter_html']['settings']['filter_html_nofollow']);
     $this->assertIdentical(72, $filters['filter_url']['settings']['filter_url_length']);
     // Check that the PHP code filter is converted to filter_null.
     $filters = FilterFormat::load('php_code')->get('filters');
     $this->assertTrue(isset($filters['filter_null']));
 }
Exemplo n.º 18
0
 /**
  * Sets up the test.
  */
 protected function setUp()
 {
     parent::setUp();
     $this->installEntitySchema('user');
     $this->installSchema('system', ['sequences']);
     $this->installConfig(['filter', 'filter_test']);
     // Filter tips link to the full-page.
     \Drupal::service('router.builder')->rebuild();
     /* @var \Drupal\Core\Render\ElementInfoManager $manager */
     $manager = \Drupal::service('plugin.manager.element_info');
     $manager->clearCachedDefinitions();
     $manager->getDefinitions();
     /* @var \Drupal\filter\FilterFormatInterface $filter_test_format */
     $filter_test_format = FilterFormat::load('filter_test');
     /* @var \Drupal\user\RoleInterface $role */
     $role = Role::create(['id' => 'admin', 'label' => 'admin']);
     $role->grantPermission($filter_test_format->getPermissionName());
     $role->save();
     $this->testUser = User::create(['name' => 'foobar', 'mail' => '*****@*****.**']);
     $this->testUser->addRole($role->id());
     $this->testUser->save();
     \Drupal::service('current_user')->setAccount($this->testUser);
 }
Exemplo n.º 19
0
 /**
  * Tests updating a filter format during import.
  */
 protected function doFilterFormatUpdate()
 {
     // Create a test filter format with a known label.
     $name = 'filter.format.plain_text';
     /** @var $entity \Drupal\filter\Entity\FilterFormat */
     $entity = FilterFormat::load('plain_text');
     $plugin_collection = $entity->getPluginCollections()['filters'];
     $filters = $entity->get('filters');
     $this->assertIdentical(72, $filters['filter_url']['settings']['filter_url_length']);
     $filters['filter_url']['settings']['filter_url_length'] = 100;
     $entity->set('filters', $filters);
     $entity->save();
     $this->assertIdentical($filters, $entity->get('filters'));
     $this->assertIdentical($filters, $plugin_collection->getConfiguration());
     $filters['filter_url']['settings']['filter_url_length'] = -100;
     $entity->getPluginCollections()['filters']->setConfiguration($filters);
     $entity->save();
     $this->assertIdentical($filters, $entity->get('filters'));
     $this->assertIdentical($filters, $plugin_collection->getConfiguration());
     // Read the existing data, and prepare an altered version in sync.
     $custom_data = $original_data = $this->container->get('config.storage')->read($name);
     $custom_data['filters']['filter_url']['settings']['filter_url_length'] = 100;
     $this->assertConfigUpdateImport($name, $original_data, $custom_data);
 }
Exemplo n.º 20
0
 /**
  * Tests that filter format dependency removal works.
  *
  * Ensure that modules providing filter plugins are required when the plugin
  * is in use, and that only disabled plugins are removed from format
  * configuration entities rather than the configuration entities being
  * deleted.
  *
  * @see \Drupal\filter\Entity\FilterFormat::onDependencyRemoval()
  * @see filter_system_info_alter()
  */
 public function testDependencyRemoval()
 {
     $this->installSchema('user', array('users_data'));
     $filter_format = \Drupal\filter\Entity\FilterFormat::load('filtered_html');
     // Disable the filter_test_restrict_tags_and_attributes filter plugin but
     // have custom configuration so that the filter plugin is still configured
     // in filtered_html the filter format.
     $filter_config = ['weight' => 20, 'status' => 0];
     $filter_format->setFilterConfig('filter_test_restrict_tags_and_attributes', $filter_config)->save();
     // Use the get method to match the assert after the module has been
     // uninstalled.
     $filters = $filter_format->get('filters');
     $this->assertTrue(isset($filters['filter_test_restrict_tags_and_attributes']), 'The filter plugin filter_test_restrict_tags_and_attributes is configured by the filtered_html filter format.');
     drupal_static_reset('filter_formats');
     \Drupal::entityManager()->getStorage('filter_format')->resetCache();
     $module_data = _system_rebuild_module_data();
     $this->assertFalse(isset($module_data['filter_test']->info['required']), 'The filter_test module is required.');
     // Verify that a dependency exists on the module that provides the filter
     // plugin since it has configuration for the disabled plugin.
     $this->assertEqual(['module' => ['filter_test']], $filter_format->getDependencies());
     // Uninstall the module.
     \Drupal::service('module_installer')->uninstall(array('filter_test'));
     // Verify the filter format still exists but the dependency and filter is
     // gone.
     \Drupal::entityManager()->getStorage('filter_format')->resetCache();
     $filter_format = \Drupal\filter\Entity\FilterFormat::load('filtered_html');
     $this->assertEqual([], $filter_format->getDependencies());
     // Use the get method since the FilterFormat::filters() method only returns
     // existing plugins.
     $filters = $filter_format->get('filters');
     $this->assertFalse(isset($filters['filter_test_restrict_tags_and_attributes']), 'The filter plugin filter_test_restrict_tags_and_attributes is not configured by the filtered_html filter format.');
 }
Exemplo n.º 21
0
 /**
  * Tests format disabling.
  */
 public function testDisableFormatWithEditor()
 {
     $formats = ['monocerus' => 'Monocerus', 'tattoo' => 'Tattoo'];
     // Install the node module.
     $this->container->get('module_installer')->install(['node']);
     $this->resetAll();
     // Create a new node type and attach the 'body' field to it.
     $node_type = NodeType::create(['type' => Unicode::strtolower($this->randomMachineName())]);
     $node_type->save();
     node_add_body_field($node_type, $this->randomString());
     $permissions = ['administer filters', "edit any {$node_type->id()} content"];
     foreach ($formats as $format => $name) {
         // Create a format and add an editor to this format.
         $this->addEditorToNewFormat($format, $name);
         // Add permission for this format.
         $permissions[] = "use text format {$format}";
     }
     // Create a node having the body format value 'moncerus'.
     $node = Node::create(['type' => $node_type->id(), 'title' => $this->randomString()]);
     $node->body->value = $this->randomString(100);
     $node->body->format = 'monocerus';
     $node->save();
     // Log in as an user able to use both formats and edit nodes of created type.
     $account = $this->drupalCreateUser($permissions);
     $this->drupalLogin($account);
     // The node edit page header.
     $text = t('<em>Edit @type</em> @title', array('@type' => $node_type->label(), '@title' => $node->label()));
     // Go to node edit form.
     $this->drupalGet('node/' . $node->id() . '/edit');
     $this->assertRaw($text);
     // Disable the format assigned to the 'body' field of the node.
     FilterFormat::load('monocerus')->disable()->save();
     // Edit again the node.
     $this->drupalGet('node/' . $node->id() . '/edit');
     $this->assertRaw($text);
 }
Exemplo n.º 22
0
 /**
  * Tests if text format is available to a role.
  */
 function testFormatRoles()
 {
     // Get the role ID assigned to the regular user.
     $roles = $this->webUser->getRoles(TRUE);
     $rid = $roles[0];
     // Check that this role appears in the list of roles that have access to an
     // allowed text format, but does not appear in the list of roles that have
     // access to a disallowed text format.
     $this->assertTrue(in_array($rid, array_keys(filter_get_roles_by_format($this->allowedFormat))), 'A role which has access to a text format appears in the list of roles that have access to that format.');
     $this->assertFalse(in_array($rid, array_keys(filter_get_roles_by_format($this->disallowedFormat))), 'A role which does not have access to a text format does not appear in the list of roles that have access to that format.');
     // Check that the correct text format appears in the list of formats
     // available to that role.
     $this->assertTrue(in_array($this->allowedFormat->id(), array_keys(filter_get_formats_by_role($rid))), 'A text format which a role has access to appears in the list of formats available to that role.');
     $this->assertFalse(in_array($this->disallowedFormat->id(), array_keys(filter_get_formats_by_role($rid))), 'A text format which a role does not have access to does not appear in the list of formats available to that role.');
     // Check that the fallback format is always allowed.
     $this->assertEqual(filter_get_roles_by_format(FilterFormat::load(filter_fallback_format())), user_role_names(), 'All roles have access to the fallback format.');
     $this->assertTrue(in_array(filter_fallback_format(), array_keys(filter_get_formats_by_role($rid))), 'The fallback format appears in the list of allowed formats for any role.');
 }
    /**
     * Tests the entity formatter.
     */
    public function testEntityFormatter()
    {
        $formatter = 'entity_reference_entity_view';
        $field_name = $this->fieldName;
        // Create the entity that will have the entity reference field.
        $referencing_entity = entity_create($this->entityType, array('name' => $this->randomMachineName()));
        $referencing_entity->save();
        $referencing_entity->{$field_name}->entity = $this->referencedEntity;
        $referencing_entity->{$field_name}->access = TRUE;
        // Build the renderable array for the entity reference field.
        $items = $referencing_entity->get($field_name);
        $build = $items->view(array('type' => $formatter));
        $expected_rendered_name_field = '<div class="field field-entity-test--name field-name-name field-type-string field-label-hidden">
    <div class="field-items">
          <div class="field-item">' . $this->referencedEntity->label() . '</div>
      </div>
</div>
';
        $expected_rendered_body_field = '<div class="field field-entity-test--body field-name-body field-type-text field-label-above">
      <div class="field-label">Body:&nbsp;</div>
    <div class="field-items">
          <div class="field-item"><p>Hello, world!</p></div>
      </div>
</div>
';
        drupal_render($build[0]);
        $this->assertEqual($build[0]['#markup'], 'default | ' . $this->referencedEntity->label() . $expected_rendered_name_field . $expected_rendered_body_field, format_string('The markup returned by the @formatter formatter is correct.', array('@formatter' => $formatter)));
        $expected_cache_tags = Cache::mergeTags(\Drupal::entityManager()->getViewBuilder($this->entityType)->getCacheTag(), $this->referencedEntity->getCacheTag(), FilterFormat::load('full_html')->getCacheTag());
        $this->assertEqual($build[0]['#cache']['tags'], $expected_cache_tags, format_string('The @formatter formatter has the expected cache tags.', array('@formatter' => $formatter)));
    }
    /**
     * Tests the entity formatter.
     */
    public function testEntityFormatter()
    {
        /** @var \Drupal\Core\Render\RendererInterface $renderer */
        $renderer = $this->container->get('renderer');
        $formatter = 'entity_reference_entity_view';
        $build = $this->buildRenderArray([$this->referencedEntity, $this->unsavedReferencedEntity], $formatter);
        // Test the first field item.
        $expected_rendered_name_field_1 = '
            <div class="field field--name-name field--type-string field--label-hidden field__item">' . $this->referencedEntity->label() . '</div>
      ';
        $expected_rendered_body_field_1 = '
  <div class="clearfix text-formatted field field--name-body field--type-text field--label-above">
    <div class="field__label">Body</div>
              <div class="field__item"><p>Hello, world!</p></div>
          </div>
';
        $renderer->renderRoot($build[0]);
        $this->assertEqual($build[0]['#markup'], 'default | ' . $this->referencedEntity->label() . $expected_rendered_name_field_1 . $expected_rendered_body_field_1, sprintf('The markup returned by the %s formatter is correct for an item with a saved entity.', $formatter));
        $expected_cache_tags = Cache::mergeTags(\Drupal::entityManager()->getViewBuilder($this->entityType)->getCacheTags(), $this->referencedEntity->getCacheTags());
        $expected_cache_tags = Cache::mergeTags($expected_cache_tags, FilterFormat::load('full_html')->getCacheTags());
        $this->assertEqual($build[0]['#cache']['tags'], $expected_cache_tags, format_string('The @formatter formatter has the expected cache tags.', array('@formatter' => $formatter)));
        // Test the second field item.
        $renderer->renderRoot($build[1]);
        $this->assertEqual($build[1]['#markup'], $this->unsavedReferencedEntity->label(), sprintf('The markup returned by the %s formatter is correct for an item with a unsaved entity.', $formatter));
    }
Exemplo n.º 25
0
 /**
  * Returns whether the text format has transformation filters.
  *
  * @param int $format_id
  *   A text format ID.
  *
  * @return bool
  */
 protected function textFormatHasTransformationFilters($format_id)
 {
     $format = FilterFormat::load($format_id);
     return (bool) count(array_intersect(array(FilterInterface::TYPE_TRANSFORM_REVERSIBLE, FilterInterface::TYPE_TRANSFORM_IRREVERSIBLE), $format->getFiltertypes()));
 }
Exemplo n.º 26
0
// Load 'adminisztator' user role.
$role = \Drupal\user\Entity\Role::load('adminisztrator');
$permissions = ['administer advanced forum', 'administer advanced forum', 'administer blocks', 'use PHP for settings', 'administer CAPTCHA settings', 'administer comments', 'administer contact forms', 'administer filters', 'administer forums', 'delete any forum content', 'delete own forum content', 'edit any forum content', 'edit own forum content', 'create images', 'delete any images', 'delete own images', 'edit any images', 'edit own images', 'view original images', 'attach images', 'administer languages', 'translate interface', 'administer login destination', 'administer mass contact', 'choose whether to archive mass contact messages', 'send mass contact attachments', 'send mass contact e-mails', 'send to users in the Wesnoth felhasználók category', 'administer menu', 'access content', 'administer content types', 'administer nodes', 'access content overview', 'create mass_contact content', 'create page content', 'delete any mass_contact content', 'delete any page content', 'delete any profile content', 'delete any story content', 'delete own mass_contact content', 'delete own page content', 'delete own profile content', 'delete own story content', 'delete revisions', 'edit any mass_contact content', 'edit any page content', 'edit any profile content', 'edit any story content', 'edit own mass_contact content', 'edit own page content', 'revert revisions', 'view revisions', 'administer url aliases', 'create url aliases', 'administer pathauto', 'notify of path changes', 'cancel own vote', 'create poll content', 'delete any poll content', 'delete own poll content', 'edit any poll content', 'edit own poll content', 'inspect all votes', 'administer privatemsg settings', 'read all private messages', 'administer search', 'administer smileys', 'access administration pages', 'access site reports', 'administer actions', 'administer files', 'administer site configuration', 'select different theme', 'administer taxonomy', 'administer taxonomy images', 'can disable taxonomy images', 'administer permissions', 'administer users', 'change own username', 'access all views', 'administer views', 'administer voting api', 'access mwb', 'access wesnoth admin', 'access wesnoth replays', 'administer mwb', 'administer wesnoth replays', 'edit any wesnoth replays', 'edit jelentkezesek', 'edit own wesnoth replays', 'use text format alakhu', 'administer comment types', 'administer display modes', 'administer comment display', 'administer comment fields', 'administer comment form display', 'administer node display', 'administer node fields', 'administer node form display', 'administer block_content display', 'administer block_content fields', 'administer block_content form display', 'administer poll display', 'administer poll fields', 'administer poll form display', 'administer taxonomy_term display', 'administer taxonomy_term fields', 'administer taxonomy_term form display', 'administer user display', 'administer user fields', 'administer user form display', 'administer polls', 'access polls', 'administer modules', 'administer software updates', 'administer themes', 'link to any page', 'access site in maintenance mode', 'view the administration theme', 'administer account settings'];
foreach ($permissions as $p) {
    $role->grantPermission($p);
}
$role->setIsAdmin(true);
$role->save();
// Set 'hu' as the default language
$langcode = 'hu';
$language = \Drupal\language\Entity\ConfigurableLanguage::load($langcode);
// From install.core.inc
\Drupal::configFactory()->getEditable('system.site')->set('langcode', $langcode)->set('default_langcode', $langcode)->save();
\Drupal::service('language.default')->set($language);
// Load 'alakhu' format and remove null filter.
$format = \Drupal\filter\Entity\FilterFormat::load('alakhu');
$filters = $format->filters();
$filters->removeInstanceID('filter_null');
// $filters->removeFilter('filter_null');
$format->save();
// Create 'alakhu' editor.
/*
$ePM = \Drupal::service('plugin.manager.editor');
$plugin = $ePM->createInstance('ckeditor');
// $plugin = $this->ckeditorPluginManager->createInstance($plugin_id);

// $editor = \Drupal\editor\Entity\Editor::create(['id'=>'alakhu', 'plugin_id'=>'ckeditor']);
// From Entity.php
$values=['id'=>'alakhu'];
$eTM = \Drupal::entityTypeManager();
// print_r($eTM->getDefinitions());
Exemplo n.º 27
0
 /**
  * Builds a translation form element.
  *
  * @param array $data
  *   Data of the translation.
  * @param LocalTaskItem $item
  *   The LocalTaskItem.
  * @param string $zebra
  *   Tell is translation is odd or even.
  *
  * @return array
  *   Render array with the translation element.
  */
 private function formElement(array $data, LocalTaskItem $item, &$zebra)
 {
     static $flip = array('even' => 'odd', 'odd' => 'even');
     $form = [];
     $job = $item->getJobItem()->getJob();
     $language_list = \Drupal::languageManager()->getLanguages();
     foreach (Element::children($data) as $key) {
         if (isset($data[$key]['#text']) && \Drupal::service('tmgmt.data')->filterData($data[$key])) {
             // The char sequence '][' confuses the form API so we need to replace
             // it.
             $target_key = str_replace('][', '|', $key);
             $zebra = $flip[$zebra];
             $form[$target_key] = array('#tree' => TRUE, '#theme' => 'tmgmt_local_translation_form_element', '#ajaxid' => Html::getUniqueId('tmgmt-local-element-' . $key), '#parent_label' => $data[$key]['#parent_label'], '#zebra' => $zebra);
             $form[$target_key]['status'] = array('#theme' => 'tmgmt_local_translation_form_element_status', '#value' => $this->entity->isCompleted() ? TMGMT_DATA_ITEM_STATE_COMPLETED : $data[$key]['#status']);
             // Manage the height of the texteareas, depending on the lenght of the
             // description. The minimum number of rows is 3 and the maximum is 15.
             $rows = ceil(strlen($data[$key]['#text']) / 100);
             if ($rows < 3) {
                 $rows = 3;
             } elseif ($rows > 15) {
                 $rows = 15;
             }
             $form[$target_key]['source'] = ['#type' => 'textarea', '#value' => $data[$key]['#text'], '#title' => t('Source'), '#disabled' => TRUE, '#rows' => $rows];
             $form[$target_key]['translation'] = ['#type' => 'textarea', '#default_value' => isset($data[$key]['#translation']['#text']) ? $data[$key]['#translation']['#text'] : NULL, '#title' => t('Translation'), '#disabled' => !$item->isPending(), '#rows' => $rows, '#allow_focus' => TRUE];
             if (!empty($data[$key]['#format']) && \Drupal::config('tmgmt.settings')->get('respect_text_format') == '1') {
                 $format_id = $data[$key]['#format'];
                 /** @var \Drupal\filter\Entity\FilterFormat $format */
                 $format = FilterFormat::load($format_id);
                 if ($format && $format->access('use')) {
                     // In case a user has permission to translate the content using
                     // selected text format, add a format id into the list of allowed
                     // text formats. Otherwise, no text format will be used.
                     $form[$target_key]['source']['#allowed_formats'] = [$format_id];
                     $form[$target_key]['translation']['#allowed_formats'] = [$format_id];
                     $form[$target_key]['source']['#type'] = 'text_format';
                     $form[$target_key]['translation']['#type'] = 'text_format';
                 }
             }
             $form[$target_key]['actions'] = array('#type' => 'container', '#access' => $item->isPending());
             $status = $item->getData(\Drupal::service('tmgmt.data')->ensureArrayKey($key), '#status');
             if ($status == TMGMT_DATA_ITEM_STATE_TRANSLATED) {
                 $form[$target_key]['actions']['reject-' . $target_key] = array('#type' => 'submit', '#value' => '✗', '#attributes' => array('title' => t('Reject')), '#name' => 'reject-' . $target_key, '#submit' => ['::save', '::submitStatus'], '#ajax' => array('callback' => '::ajaxReviewForm', 'wrapper' => $form[$target_key]['#ajaxid']), '#tmgmt_local_action' => 'reject', '#tmgmt_local_key' => str_replace('][', '|', $key));
             } else {
                 $form[$target_key]['actions']['finish-' . $target_key] = array('#type' => 'submit', '#value' => '✓', '#attributes' => array('title' => t('Finish')), '#name' => 'finish-' . $target_key, '#submit' => ['::save', '::submitStatus'], '#ajax' => array('callback' => '::ajaxReviewForm', 'wrapper' => $form[$target_key]['#ajaxid']), '#tmgmt_local_action' => 'finish', '#tmgmt_local_key' => str_replace('][', '|', $key));
             }
         }
     }
     return $form;
 }
Exemplo n.º 28
0
 /**
  * Build form elements for the review form using flattened data items.
  *
  * @todo Mention in the api documentation that the char '|' is not allowed in
  * field names.
  *
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   The current state of the form.
  * @param array $data
  *   Flattened array of translation data items.
  * @param string $parent_key
  *   The key for $data.
  *
  * @return array|NULL
  *   Render array with the form element, or NULL if the text is not set.
  */
 function reviewFormElement(FormStateInterface $form_state, $data, $parent_key)
 {
     $review_element = NULL;
     foreach (Element::children($data) as $key) {
         $data_item = $data[$key];
         if (isset($data_item['#text']) && \Drupal::service('tmgmt.data')->filterData($data_item)) {
             // The char sequence '][' confuses the form API so we need to replace
             // it when using it for the form field name.
             $field_name = str_replace('][', '|', $key);
             // Ensure that the review form structure is initialized.
             $review_element['#theme'] = 'tmgmt_data_items_form';
             $review_element['#ajaxid'] = $ajax_id = tmgmt_review_form_element_ajaxid($parent_key);
             $review_element['#top_label'] = array_shift($data_item['#parent_label']);
             $leave_label = array_pop($data_item['#parent_label']);
             // Data items are grouped based on their key hierarchy, calculate the
             // group key and ensure that the group is initialized.
             $group_name = substr($field_name, 0, strrpos($field_name, '|'));
             if (empty($group_name)) {
                 $group_name = '_none';
             }
             if (!isset($review_element[$group_name])) {
                 $review_element[$group_name] = ['#group_label' => $data_item['#parent_label']];
             }
             // Initialize the form element for the given data item and make it
             // available as $element.
             $review_element[$group_name][$field_name] = array('#tree' => TRUE);
             $item_element =& $review_element[$group_name][$field_name];
             $item_element['label']['#markup'] = $leave_label;
             $item_element['status'] = $this->buildStatusRenderArray($this->entity->isAccepted() ? TMGMT_DATA_ITEM_STATE_ACCEPTED : $data_item['#status']);
             $item_element['actions'] = array('#type' => 'container');
             $item_element['below_actions'] = ['#type' => 'container'];
             // Check if the field has a text format attached and check access.
             if (!empty($data_item['#format'])) {
                 $format_id = $data_item['#format'];
                 /** @var \Drupal\filter\Entity\FilterFormat $format */
                 $format = FilterFormat::load($format_id);
                 if (!$format || !$format->access('use')) {
                     $item_element['actions']['#access'] = FALSE;
                     $form_state->set('accept_item', FALSE);
                 }
             }
             $item_element['actions'] += $this->buildActions($data_item, $key, $field_name, $ajax_id);
             // Manage the height of the textareas, depending on the length of the
             // description. The minimum number of rows is 3 and the maximum is 15.
             $rows = ceil(strlen($data_item['#text']) / 100);
             $rows = min($rows, 15);
             $rows = max($rows, 3);
             // Build source and translation areas.
             $item_element = $this->buildSource($item_element, $data_item, $rows, $form_state);
             $item_element = $this->buildTranslation($item_element, $data_item, $rows, $form_state);
             $item_element = $this->buildChangedSource($item_element, $form_state, $field_name, $key, $ajax_id);
             if (isset($form_state->get('validation_messages')[$field_name])) {
                 $item_element['below']['validation'] = ['#type' => 'container', '#attributes' => ['class' => ['tmgmt_validation_message', 'messages', 'messages--warning']], 'message' => ['#markup' => Html::escape($form_state->get('validation_messages')[$field_name])]];
             }
             // Give the translator UI controller a chance to affect the data item element.
             if ($this->entity->hasTranslator()) {
                 $item_element = \Drupal::service('plugin.manager.tmgmt.translator')->createUIInstance($this->entity->getTranslator()->getPluginId())->reviewDataItemElement($item_element, $form_state, $key, $parent_key, $data_item, $this->entity);
                 // Give the source ui controller a chance to affect the data item element.
                 $item_element = \Drupal::service('plugin.manager.tmgmt.source')->createUIInstance($this->entity->getPlugin())->reviewDataItemElement($item_element, $form_state, $key, $parent_key, $data_item, $this->entity);
             }
         }
     }
     return $review_element;
 }
 /**
  * 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.
     $cache_tags = array();
     $all_assets = array();
     $all_post_render_cache_callbacks = array();
     foreach ($filters as $filter) {
         if ($filter_must_be_applied($filter)) {
             $result = $filter->process($text, $langcode);
             $all_assets[] = $result->getAssets();
             $cache_tags = Cache::mergeTags($cache_tags, $result->getCacheTags());
             $all_post_render_cache_callbacks[] = $result->getPostRenderCacheCallbacks();
             $text = $result->getProcessedText();
         }
     }
     // Filtering done, store in #markup.
     $element['#markup'] = $text;
     // Collect all cache tags.
     if (isset($element['#cache']) && isset($element['#cache']['tags'])) {
         // Merge the original cache tags array.
         $cache_tags = Cache::mergeTags($cache_tags, $element['#cache']['tags']);
     }
     // Prepend the text format's cache tags array.
     $cache_tags = Cache::mergeTags($cache_tags, $format->getCacheTag());
     $element['#cache']['tags'] = $cache_tags;
     // Collect all attached assets.
     if (isset($element['#attached'])) {
         // Prepend the original attached assets array.
         array_unshift($all_assets, $element['#attached']);
     }
     $element['#attached'] = NestedArray::mergeDeepArray($all_assets);
     // Collect all #post_render_cache callbacks.
     if (isset($element['#post_render_cache'])) {
         // Prepend the original attached #post_render_cache array.
         array_unshift($all_assets, $element['#post_render_cache']);
     }
     $element['#post_render_cache'] = NestedArray::mergeDeepArray($all_post_render_cache_callbacks);
     return $element;
 }
Exemplo n.º 30
0
 /**
  * Helper function for testTextfieldWidgetsFormatted().
  */
 function _testTextfieldWidgetsFormatted($field_type, $widget_type)
 {
     /** @var \Drupal\Core\Render\RendererInterface $renderer */
     $renderer = $this->container->get('renderer');
     // Create a field.
     $field_name = Unicode::strtolower($this->randomMachineName());
     $field_storage = FieldStorageConfig::create(array('field_name' => $field_name, 'entity_type' => 'entity_test', 'type' => $field_type));
     $field_storage->save();
     FieldConfig::create(['field_storage' => $field_storage, 'bundle' => 'entity_test', 'label' => $this->randomMachineName() . '_label'])->save();
     entity_get_form_display('entity_test', 'entity_test', 'default')->setComponent($field_name, array('type' => $widget_type))->save();
     entity_get_display('entity_test', 'entity_test', 'full')->setComponent($field_name)->save();
     // Disable all text formats besides the plain text fallback format.
     $this->drupalLogin($this->adminUser);
     foreach (filter_formats() as $format) {
         if (!$format->isFallbackFormat()) {
             $this->drupalPostForm('admin/config/content/formats/manage/' . $format->id() . '/disable', array(), t('Disable'));
         }
     }
     $this->drupalLogin($this->webUser);
     // Display the creation form. Since the user only has access to one format,
     // no format selector will be displayed.
     $this->drupalGet('entity_test/add');
     $this->assertFieldByName("{$field_name}[0][value]", '', 'Widget is displayed');
     $this->assertNoFieldByName("{$field_name}[0][format]", '', 'Format selector is not displayed');
     // Submit with data that should be filtered.
     $value = '<em>' . $this->randomMachineName() . '</em>';
     $edit = array("{$field_name}[0][value]" => $value);
     $this->drupalPostForm(NULL, $edit, t('Save'));
     preg_match('|entity_test/manage/(\\d+)|', $this->url, $match);
     $id = $match[1];
     $this->assertText(t('entity_test @id has been created.', array('@id' => $id)), 'Entity was created');
     // Display the entity.
     $entity = EntityTest::load($id);
     $display = entity_get_display($entity->getEntityTypeId(), $entity->bundle(), 'full');
     $content = $display->build($entity);
     $this->setRawContent($renderer->renderRoot($content));
     $this->assertNoRaw($value, 'HTML tags are not displayed.');
     $this->assertEscaped($value, 'Escaped HTML is displayed correctly.');
     // Create a new text format that does not escape HTML, and grant the user
     // access to it.
     $this->drupalLogin($this->adminUser);
     $edit = array('format' => Unicode::strtolower($this->randomMachineName()), 'name' => $this->randomMachineName());
     $this->drupalPostForm('admin/config/content/formats/add', $edit, t('Save configuration'));
     filter_formats_reset();
     $format = FilterFormat::load($edit['format']);
     $format_id = $format->id();
     $permission = $format->getPermissionName();
     $roles = $this->webUser->getRoles();
     $rid = $roles[0];
     user_role_grant_permissions($rid, array($permission));
     $this->drupalLogin($this->webUser);
     // Display edition form.
     // We should now have a 'text format' selector.
     $this->drupalGet('entity_test/manage/' . $id . '/edit');
     $this->assertFieldByName("{$field_name}[0][value]", NULL, 'Widget is displayed');
     $this->assertFieldByName("{$field_name}[0][format]", NULL, 'Format selector is displayed');
     // Edit and change the text format to the new one that was created.
     $edit = array("{$field_name}[0][format]" => $format_id);
     $this->drupalPostForm(NULL, $edit, t('Save'));
     $this->assertText(t('entity_test @id has been updated.', array('@id' => $id)), 'Entity was updated');
     // Display the entity.
     $this->container->get('entity.manager')->getStorage('entity_test')->resetCache(array($id));
     $entity = EntityTest::load($id);
     $display = entity_get_display($entity->getEntityTypeId(), $entity->bundle(), 'full');
     $content = $display->build($entity);
     $this->setRawContent($renderer->renderRoot($content));
     $this->assertRaw($value, 'Value is displayed unfiltered');
 }