Newer
Older
<?php
Jennifer Hodgdon
committed
* Framework for handling the filtering of content.
Angie Byron
committed
Alex Pott
committed
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\String;
Angie Byron
committed
use Drupal\Component\Utility\Xss;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Language\Language;
Angie Byron
committed
use Drupal\Core\Render\Element;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Template\Attribute;
use Drupal\filter\FilterFormatInterface;
use Drupal\filter\Plugin\FilterInterface;
use Symfony\Component\HttpFoundation\Request;
Angie Byron
committed
Dries Buytaert
committed
* Implements hook_help().
function filter_help($route_name, Request $request) {
switch ($route_name) {
case 'help.page.filter':
Angie Byron
committed
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('The Filter module allows administrators to configure text formats. Text formats define the HTML tags, codes, and other input allowed in text entered in the site and they defend your web site against potentially damaging input from malicious users. A visual text editor can be associated with the text formats by using the <a href="!editor_help">Text Editor module</a>. For more information, see <a href="!filter_do">the online documentation for the Filter module</a>.', array('!filter_do' => 'https://drupal.org/documentation/modules/filter/','!editor_help' => \Drupal::url('help.page', array('name' => 'editor')))) . '</p>';
Angie Byron
committed
$output .= '<h3>' . t('Uses') . '</h3>';
$output .= '<dl>';
$output .= '<dt>' . t('Managing text formats') . '</dt>';
$output .= '<dd>' . t('You can create and edit text formats on the <a href="!formats">Text formats page</a> (if the Text Editor module is enabled, this page is named Text formats and editors). One text format is included by default: Plain text (which removes all HTML tags). Additional text formats may be created during installation. You can create a text format by clicking "<a href="!add_format">Add text format</a>".', array('!formats' => \Drupal::url('filter.admin_overview'),'!add_format' => \Drupal::url('filter.format_add'))) . '</dd>';
$output .= '<dt>' . t('Assigning roles to text formats') . '</dt>';
$output .= '<dd>' . t('You can define which users will be able to use each text format by selecting roles. To ensure security, anonymous and untrusted users should only have access to text formats that restrict them to either plain text or a safe set of HTML tags. This is because HTML tags can allow embedding malicious links or scripts in text. More trusted registered users may be granted permission to use less restrictive text formats in order to create rich text. <strong>Improper text format configuration is a security risk</strong>.') . '</dd>';
$output .= '<dt>' . t('Selecting filters') . '</dt>';
$output .= '<dd><p>' . t('Each text format uses filters that add, remove, or transform elements within user-entered text. For example, one filter removes unapproved HTML tags, while another transforms URLs into clickable links. Filters are applied in a specific order and do not change the actual content, but instead, modify it temporarily before it is displayed.') . '<p>';
$output .= '<p>' . t('Each filter can have additional configuration options. For example, for the "Limit allowed HTML tags" filter you need to define the list of HTML tags that the filter leaves in the text.') . '</p></dd>';
$output .= '<dt>' . t('Enabling text formats for field editing') . '</dt>';
$output .= '<dd>' . t('In the field settings for a field that supports text formats (such as Long text), you can enable the use of text formats by choosing "Filtered text (user selects text format)" under "Text processing". See the <a href="!field_help">Field module help</a> and the <a href="!field_ui_help">Field UI help</a> pages for general information on fields and how to create and manage them.', array('!field_help' => \Drupal::url('help.page', array('name' => 'field')), '!field_ui_help' => \Drupal::url('help.page', array('name' => 'field_ui')))) . '</dd>';
Angie Byron
committed
$output .= '<dt>' . t('Choosing a text format') . '</dt>';
$output .= '<dd>' . t('When creating or editing data in a field that has text formats enabled, users can select the format under the field from the Text format select list.') . '</dd>';
Angie Byron
committed
$output .= '</dl>';
Dries Buytaert
committed
return $output;
Dries Buytaert
committed
case 'filter.admin_overview':
Angie Byron
committed
$output = '<p>' . t('Text formats define the HTML tags, code, and other formatting that can be used when entering text. <strong>Improper text format configuration is a security risk</strong>. Learn more on the <a href="@filterhelp">Filter module help page</a>.', array('@filterhelp' => url('admin/help/filter'))) . '</p>';
Dries Buytaert
committed
$output .= '<p>' . t('Text formats are presented on content editing pages in the order defined on this page. The first format available to a user will be selected by default.') . '</p>';
return $output;
Dries Buytaert
committed
case 'filter.format_edit':
Dries Buytaert
committed
$output = '<p>' . t('A text format contains filters that change the user input, for example stripping out malicious HTML or making URLs clickable. Filters are executed from top to bottom and the order is important, since one filter may prevent another filter from doing its job. For example, when URLs are converted into links before disallowed HTML tags are removed, all links may be removed. When this happens, the order of filters may need to be re-arranged.') . '</p>';
return $output;
Steven Wittens
committed
}
}
Dries Buytaert
committed
/**
Dries Buytaert
committed
* Implements hook_theme().
Dries Buytaert
committed
*/
function filter_theme() {
return array(
'filter_tips' => array(
'variables' => array('tips' => NULL, 'long' => FALSE),
'template' => 'filter-tips',
Dries Buytaert
committed
),
'text_format_wrapper' => array(
'variables' => array(
'children' => NULL,
'description' => NULL,
'attributes' => array(),
),
'template' => 'text-format-wrapper',
),
Angie Byron
committed
'filter_guidelines' => array(
'variables' => array('format' => NULL),
'template' => 'filter-guidelines',
Angie Byron
committed
),
'filter_caption' => array(
'variables' => array(
'node' => NULL,
'tag' => NULL,
'caption' => NULL,
'align' => NULL,
),
'template' => 'filter-caption',
)
Dries Buytaert
committed
);
}
/**
* Implements hook_element_info().
*
* @see filter_process_format()
Jennifer Hodgdon
committed
* @see text_format_wrapper()
*/
function filter_element_info() {
$type['text_format'] = array(
'#process' => array('filter_process_format'),
'#base_type' => 'textarea',
'#theme_wrappers' => array('text_format_wrapper'),
);
return $type;
}
Dries Buytaert
committed
* Implements hook_permission().
function filter_permission() {
$perms['administer filters'] = array(
Dries Buytaert
committed
'title' => t('Administer text formats and filters'),
Angie Byron
committed
'description' => t('Define how text is handled by combining filters into <a href="@url">text formats</a>.', array(
'@url' => url('admin/config/content/formats'),
)),
Dries Buytaert
committed
'restrict access' => TRUE,
);
// Generate permissions for each text format. Warn the administrator that any
// of them are potentially unsafe.
foreach (filter_formats() as $format) {
if ($permission = $format->getPermissionName()) {
$format_name_replacement = l($format->label(), 'admin/config/content/formats/manage/' . $format->id());
$perms[$permission] = array(
'title' => t("Use the !text_format text format", array('!text_format' => $format_name_replacement,)),
'description' => String::placeholder(t('Warning: This permission may have security implications depending on how the text format is configured.')),
);
}
}
return $perms;
}
/**
* Retrieves a list of enabled text formats, ordered by weight.
*
* @param \Drupal\Core\Session\AccountInterface|null $account
* (optional) If provided, only those formats that are allowed for this user
* account will be returned. All enabled formats will be returned otherwise.
* Defaults to NULL.
Jennifer Hodgdon
committed
*
* @return \Drupal\filter\FilterFormatInterface[]
* An array of text format objects, keyed by the format ID and ordered by
* weight.
*
* @see filter_formats_reset()
function filter_formats(AccountInterface $account = NULL) {
Dries Buytaert
committed
$formats = &drupal_static(__FUNCTION__, array());
Steven Wittens
committed
// All available formats are cached for performance.
if (!isset($formats['all'])) {
$language_interface = \Drupal::languageManager()->getCurrentLanguage();
if ($cache = \Drupal::cache()->get("filter_formats:{$language_interface->id}")) {
$formats['all'] = $cache->data;
}
else {
catch
committed
$formats['all'] = \Drupal::entityManager()->getStorage('filter_format')->loadByProperties(array('status' => TRUE));
Angie Byron
committed
uasort($formats['all'], 'Drupal\Core\Config\Entity\ConfigEntityBase::sort');
\Drupal::cache()->set("filter_formats:{$language_interface->id}", $formats['all'], Cache::PERMANENT, array('filter_formats' => TRUE));
Dries Buytaert
committed
}
Steven Wittens
committed
// If no user was specified, return all formats.
if (!isset($account)) {
return $formats['all'];
}
// Build a list of user-specific formats.
$account_id = $account->id();
if (!isset($formats['user'][$account_id])) {
$formats['user'][$account_id] = array();
foreach ($formats['all'] as $format) {
if ($format->access('use', $account)) {
$formats['user'][$account_id][$format->format] = $format;
Steven Wittens
committed
}
}
}
return $formats['user'][$account_id];
}
Steven Wittens
committed
/**
Jennifer Hodgdon
committed
* Resets the text format caches.
*
* @see filter_formats()
*/
function filter_formats_reset() {
drupal_static_reset('filter_formats');
}
/**
* Retrieves a list of roles that are allowed to use a given text format.
*
* @param \Drupal\filter\FilterFormatInterface $format
* An object representing the text format.
Jennifer Hodgdon
committed
*
* @return array
* An array of role names, keyed by role ID.
*/
function filter_get_roles_by_format(FilterFormatInterface $format) {
// Handle the fallback format upfront (all roles have access to this format).
if ($format->isFallbackFormat()) {
return user_role_names();
Steven Wittens
committed
}
// Do not list any roles if the permission does not exist.
$permission = $format->getPermissionName();
return !empty($permission) ? user_role_names(FALSE, $permission) : array();
}
/**
* Retrieves a list of text formats that are allowed for a given role.
*
* @param $rid
* The user role ID to retrieve text formats for.
Jennifer Hodgdon
committed
*
* @return \Drupal\filter\FilterFormatInterface[]
* An array of text format objects that are allowed for the role, keyed by
* the text format ID and ordered by weight.
*/
function filter_get_formats_by_role($rid) {
$formats = array();
foreach (filter_formats() as $format) {
$roles = filter_get_roles_by_format($format);
if (isset($roles[$rid])) {
$formats[$format->id()] = $format;
}
Dries Buytaert
committed
}
return $formats;
}
/**
* Returns the ID of the default text format for a particular user.
*
* The default text format is the first available format that the user is
* allowed to access, when the formats are ordered by weight. It should
* generally be used as a default choice when presenting the user with a list
* of possible text formats (for example, in a node creation form).
*
* Conversely, when existing content that does not have an assigned text format
* needs to be filtered for display, the default text format is the wrong
* choice, because it is not guaranteed to be consistent from user to user, and
* some trusted users may have an unsafe text format set by default, which
* should not be used on text of unknown origin. Instead, the fallback format
* returned by filter_fallback_format() should be used, since that is intended
* to be a safe, consistent format that is always available to all users.
*
* @param \Drupal\Core\Session\AccountInterface|null $account
* (optional) The user account to check. Defaults to the currently logged-in
Jennifer Hodgdon
committed
* user. Defaults to NULL.
Jennifer Hodgdon
committed
*
* @return string
* The ID of the user's default text format.
*
* @see filter_fallback_format()
*/
function filter_default_format(AccountInterface $account = NULL) {
if (!isset($account)) {
$account = \Drupal::currentUser();
}
// Get a list of formats for this user, ordered by weight. The first one
// available is the user's default format.
$formats = filter_formats($account);
$format = reset($formats);
return $format->format;
}
/**
* Returns the ID of the fallback text format that all users have access to.
*
* The fallback text format is a regular text format in every respect, except
* it does not participate in the filter permission system and cannot be
Dries Buytaert
committed
* disabled. It needs to exist because any user who has permission to create
* formatted content must always have at least one text format they can use.
*
* Because the fallback format is available to all users, it should always be
* configured securely. For example, when the Filter module is installed, this
* format is initialized to output plain text. Installation profiles and site
* administrators have the freedom to configure it further.
*
Jennifer Hodgdon
committed
* Note that the fallback format is completely distinct from the default format,
* which differs per user and is simply the first format which that user has
* access to. The default and fallback formats are only guaranteed to be the
* same for users who do not have access to any other format; otherwise, the
* fallback format's weight determines its placement with respect to the user's
* other formats.
*
Jennifer Hodgdon
committed
* Any modules implementing a format deletion functionality must not delete this
* format.
Dries Buytaert
committed
*
Jennifer Hodgdon
committed
* @return
* The ID of the fallback text format.
*
Dries Buytaert
committed
* @see hook_filter_format_disable()
* @see filter_default_format()
*/
function filter_fallback_format() {
// This variable is automatically set in the database for all installations
Dries Buytaert
committed
// of Drupal. In the event that it gets disabled or deleted somehow, there
Angie Byron
committed
// is no safe default to return, since we do not want to risk making an
Dries Buytaert
committed
// existing (and potentially unsafe) text format on the site automatically
// available to all users. Returning NULL at least guarantees that this
// cannot happen.
return \Drupal::config('filter.settings')->get('fallback_format');
}
Jennifer Hodgdon
committed
* Checks if the text in a certain text format is allowed to be cached.
Dries Buytaert
committed
*
* This function can be used to check whether the result of the filtering
* process can be cached. A text format may allow caching depending on the
* filters enabled.
*
* @param string $format_id
Dries Buytaert
committed
* The text format ID to check.
Jennifer Hodgdon
committed
*
* @return bool
Dries Buytaert
committed
* TRUE if the given text format allows caching, FALSE otherwise.
function filter_format_allowcache($format_id) {
$format = $format_id ? entity_load('filter_format', $format_id) : FALSE;
Dries Buytaert
committed
return !empty($format->cache);
}
Steven Wittens
committed
/**
Jennifer Hodgdon
committed
* 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
Jennifer Hodgdon
committed
* validation stage of the Form API. You should for example never make a
* preview of content in a disallowed format.
*
* @param $text
* @param $format_id
* (optional) The machine name of the filter format to be used to filter the
* text. Defaults to the fallback format. See filter_fallback_format().
Dries Buytaert
committed
* @param $langcode
Jennifer Hodgdon
committed
* (optional) The language code of the text to be filtered, e.g. 'en' for
* English. This allows filters to be language aware so language specific
Jennifer Hodgdon
committed
* text replacement can be implemented. Defaults to an empty string.
Dries Buytaert
committed
* @param $cache
Jennifer Hodgdon
committed
* (optional) A Boolean indicating whether to cache the filtered output in the
* {cache_filter} table. The caller may set this to FALSE when the output is
* already cached elsewhere to avoid duplicate cache lookups and storage.
* Defaults to FALSE.
Angie Byron
committed
* @param array $filter_types_to_skip
* (optional) 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.
Dries Buytaert
committed
*
Jennifer Hodgdon
committed
* @return
* The filtered text.
*
Dries Buytaert
committed
* @ingroup sanitization
Angie Byron
committed
function check_markup($text, $format_id = NULL, $langcode = '', $cache = FALSE, $filter_types_to_skip = array()) {
if (!isset($format_id)) {
$format_id = filter_fallback_format();
}
Dries Buytaert
committed
// If the requested text format does not exist, the text cannot be filtered.
if (!$format = entity_load('filter_format', $format_id)) {
Angie Byron
committed
watchdog('filter', 'Missing text format: %format.', array('%format' => $format_id), WATCHDOG_ALERT);
Dries Buytaert
committed
return '';
}
Steven Wittens
committed
// Prevent FilterInterface::TYPE_HTML_RESTRICTOR from being skipped.
if (in_array(FilterInterface::TYPE_HTML_RESTRICTOR, $filter_types_to_skip)) {
$filter_types_to_skip = array_diff($filter_types_to_skip, array(FilterInterface::TYPE_HTML_RESTRICTOR));
Angie Byron
committed
}
// When certain filters should be skipped, don't perform caching.
if ($filter_types_to_skip) {
$cache = FALSE;
}
Angie Byron
committed
// Check for a cached version of this piece of text.
Dries Buytaert
committed
$cache = $cache && !empty($format->cache);
Angie Byron
committed
if ($cache) {
Dries Buytaert
committed
$cache_id = $format->format . ':' . $langcode . ':' . hash('sha256', $text);
if ($cached = \Drupal::cache('filter')->get($cache_id)) {
Angie Byron
committed
return $cached->data;
}
Angie Byron
committed
}
Dries Buytaert
committed
Angie Byron
committed
// 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);
Angie Byron
committed
// Get a complete list of filters, ordered properly.
$filters = $format->filters();
Angie Byron
committed
// Give filters the chance to escape HTML-like data such as code or formulas.
foreach ($filters as $filter) {
Angie Byron
committed
// If necessary, skip filters of a certain type.
if (in_array($filter->getType(), $filter_types_to_skip)) {
Angie Byron
committed
continue;
}
if ($filter->status) {
$text = $filter->prepare($text, $langcode, $cache, $cache_id);
}
Angie Byron
committed
}
Angie Byron
committed
// Perform filtering.
foreach ($filters as $filter) {
Angie Byron
committed
// If necessary, skip filters of a certain type.
if (in_array($filter->getType(), $filter_types_to_skip)) {
Angie Byron
committed
continue;
}
if ($filter->status) {
$text = $filter->process($text, $langcode, $cache, $cache_id);
Angie Byron
committed
Dries Buytaert
committed
// Cache the filtered text. This cache is infinitely valid. It becomes
// obsolete when $text changes (which leads to a new $cache_id). It is
// automatically flushed when the text format is updated.
// @see \Drupal\filter\Entity\FilterFormat::save()
Angie Byron
committed
if ($cache) {
\Drupal::cache('filter')->set($cache_id, $text, Cache::PERMANENT, array('filter_format' => $format->id()));
* Expands an element into a base element with text format selector attached.
*
* The form element will be expanded into two separate form elements, one
Jennifer Hodgdon
committed
* holding the original element, and the other holding the text format
* selector:
* - value: Holds the original element, having its #type changed to the value
* of #base_type or 'textarea' by default.
* - format: Holds the text format details and the text format selection,
Jennifer Hodgdon
committed
* using the text format ID specified in #format or the user's default format
* by default, if NULL.
*
* The resulting value for the element will be an array holding the value and
* the format. For example, the value for the body element will be:
* @code
Dries Buytaert
committed
* $form_state['values']['body']['value'] = 'foo';
* $form_state['values']['body']['format'] = 'foo';
* @endcode
*
* @param $element
* The form element to process. Properties used:
* - #base_type: The form element #type to use for the 'value' element.
* 'textarea' by default.
Jennifer Hodgdon
committed
* - #format: (optional) The text format ID to preselect. If NULL or not set,
Angie Byron
committed
* the default format for the current user will be used.
Dries Buytaert
committed
*
* The expanded element.
function filter_process_format($element) {
$user = \Drupal::currentUser();
// Ensure that children appear as subkeys of this element.
$element['#tree'] = TRUE;
$blacklist = array(
// Make form_builder() regenerate child properties.
'#parents',
'#id',
'#name',
// Do not copy this #process function to prevent form_builder() from
// recursing infinitely.
'#process',
// Description is handled by theme_text_format_wrapper().
'#description',
// Ensure proper ordering of children.
'#weight',
// Properties already processed for the parent element.
'#prefix',
'#suffix',
'#attached',
'#processed',
'#theme_wrappers',
);
// Move this element into sub-element 'value'.
unset($element['value']);
Angie Byron
committed
foreach (Element::properties($element) as $key) {
if (!in_array($key, $blacklist)) {
$element['value'][$key] = $element[$key];
}
}
$element['value']['#type'] = $element['#base_type'];
$element['value'] += element_info($element['#base_type']);
// Turn original element into a text format wrapper.
$element['#attached']['library'][] = 'filter/drupal.filter';
// Setup child container for the text format widget.
$element['format'] = array(
'#type' => 'container',
'#attributes' => array('class' => array('filter-wrapper')),
Angie Byron
committed
);
Angie Byron
committed
// Get a list of formats that the current user has access to.
$formats = filter_formats($user);
// Use the default format for this user if none was selected.
if (!isset($element['#format'])) {
$element['#format'] = filter_default_format($user);
}
// If multiple text formats are available, remove the fallback. The
// "always_show_fallback_choice" is a hidden variable that has no UI. It
// defaults to false.
if (!\Drupal::config('filter.settings')->get('always_show_fallback_choice')) {
Angie Byron
committed
$fallback_format = filter_fallback_format();
if ($element['#format'] !== $fallback_format && count($formats) > 1) {
unset($formats[$fallback_format]);
}
}
// Prepare text format guidelines.
$element['format']['guidelines'] = array(
'#type' => 'container',
'#attributes' => array('class' => array('filter-guidelines')),
'#weight' => 20,
$options = array();
foreach ($formats as $format) {
$options[$format->id()] = $format->label();
$element['format']['guidelines'][$format->id()] = array(
'#theme' => 'filter_guidelines',
'#format' => $format,
Angie Byron
committed
);
$element['format']['format'] = array(
'#type' => 'select',
'#title' => t('Text format'),
'#options' => $options,
'#default_value' => $element['#format'],
'#access' => count($formats) > 1,
'#weight' => 10,
'#attributes' => array('class' => array('filter-list')),
'#parents' => array_merge($element['#parents'], array('format')),
$element['format']['help'] = array(
'#type' => 'container',
'#attributes' => array('class' => array('filter-help')),
'#markup' => l(t('About text formats'), 'filter/tips', array('attributes' => array('target' => '_blank'))),
'#weight' => 0,
Dries Buytaert
committed
$all_formats = filter_formats();
Angie Byron
committed
$format_exists = isset($all_formats[$element['#format']]);
$user_has_access = isset($formats[$element['#format']]);
$user_is_admin = user_access('administer filters');
// If the stored format does not exist, administrators have to assign a new
// format.
if (!$format_exists && $user_is_admin) {
Dries Buytaert
committed
$element['format']['format']['#required'] = TRUE;
Angie Byron
committed
$element['format']['format']['#default_value'] = NULL;
// Force access to the format selector (it may have been denied above if
// the user only has access to a single format).
$element['format']['format']['#access'] = TRUE;
}
// Disable this widget, if the user is not allowed to use the stored format,
// or if the stored format does not exist. The 'administer filters' permission
// only grants access to the filter administration, not to all formats.
elseif (!$user_has_access || !$format_exists) {
Dries Buytaert
committed
// Overload default values into #value to make them unalterable.
$element['value']['#value'] = $element['value']['#default_value'];
$element['format']['format']['#value'] = $element['format']['format']['#default_value'];
// Prepend #pre_render callback to replace field value with user notice
// prior to rendering.
Angie Byron
committed
$element['value'] += array('#pre_render' => array());
Dries Buytaert
committed
array_unshift($element['value']['#pre_render'], 'filter_form_access_denied');
// Cosmetic adjustments.
if (isset($element['value']['#rows'])) {
$element['value']['#rows'] = 3;
}
$element['value']['#disabled'] = TRUE;
catch
committed
$element['value']['#resizable'] = 'none';
Dries Buytaert
committed
// Hide the text format selector and any other child element (such as text
// field's summary).
Angie Byron
committed
foreach (Element::children($element) as $key) {
Dries Buytaert
committed
if ($key != 'value') {
$element[$key]['#access'] = FALSE;
}
}
}
return $element;
}
Dries Buytaert
committed
/**
Jennifer Hodgdon
committed
* Render API callback: Hides the field value of 'text_format' elements.
Dries Buytaert
committed
*
Jennifer Hodgdon
committed
* To not break form processing and previews if a user does not have access to
* a stored text format, the expanded form elements in filter_process_format()
* are forced to take over the stored #default_values for 'value' and 'format'.
Dries Buytaert
committed
* However, to prevent the unfiltered, original #value from being displayed to
* the user, we replace it with a friendly notice here.
*
* @see filter_process_format()
*/
function filter_form_access_denied($element) {
$element['#value'] = t('This field has been disabled because you do not have sufficient permissions to edit it.');
return $element;
}
Jennifer Hodgdon
committed
* Retrieves the filter tips.
*
* @param string $format_id
Jennifer Hodgdon
committed
* The ID of the text format for which to retrieve tips, or -1 to return tips
* for all formats accessible to the current user.
* @param bool $long
Jennifer Hodgdon
committed
* (optional) Boolean indicating whether the long form of tips should be
* returned. Defaults to FALSE.
*
* @return array
Jennifer Hodgdon
committed
* An associative array of filtering tips, keyed by filter name. Each
* filtering tip is an associative array with elements:
* - tip: Tip text.
* - id: Filter ID.
function _filter_tips($format_id, $long = FALSE) {
$formats = filter_formats(\Drupal::currentUser());
// If only listing one format, extract it from the $formats array.
if ($format_id != -1) {
$formats = array($formats[$format_id]);
foreach ($format->filters() as $name => $filter) {
if ($filter->status) {
$tip = $filter->tips($long);
Dries Buytaert
committed
if (isset($tip)) {
$tips[$format->label()][$name] = array('tip' => $tip, 'id' => $name);
Dries Buytaert
committed
}
}
}
}
return $tips;
}
Angie Byron
committed
/**
* Prepares variables for text format guideline templates.
*
* Default template: filter-guidelines.html.twig.
Angie Byron
committed
*
Jennifer Hodgdon
committed
* @param array $variables
* An associative array containing:
* - format: An object representing a text format.
Angie Byron
committed
*/
function template_preprocess_filter_guidelines(&$variables) {
Dries Buytaert
committed
$format = $variables['format'];
$variables['attributes']['class'][] = 'filter-guidelines-item';
$variables['attributes']['class'][] = 'filter-guidelines-' . $format->format;
$variables['tips'] = array(
Alex Pott
committed
'#theme' => 'filter_tips',
'#tips' => _filter_tips($format->format, FALSE),
);
}
/**
* Prepares variables for text format wrapper templates.
*
* Default template: text-format-wrapper.html.twig.
*
* @param array $variables
* An associative array containing:
* - attributes: An associative array containing properties of the element.
*/
function template_preprocess_text_format_wrapper(&$variables) {
// Add element class and id for screen readers.
if (isset($variables['attributes']['aria-describedby'])) {
$variables['attributes']['class'][] = 'description';
$variables['attributes']['id'] = $variables['attributes']['aria-describedby'];
// Remove aria-describedby attribute as it shouldn't be visible here.
unset($variables['attributes']['aria-describedby']);
}
}
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
/**
* Prepares variables for filter tips templates.
*
* Default template: filter-tips.html.twig.
*
* @param array $variables
* An associative array containing:
* - tips: An array containing descriptions and a CSS ID in the form of
* 'module-name/filter-id' (only used when $long is TRUE) for each
* filter in one or more text formats. Example:
* @code
* array(
* 'Full HTML' => array(
* 0 => array(
* 'tip' => 'Web page addresses and e-mail addresses turn into links automatically.',
* 'id' => 'filter/2',
* ),
* ),
* );
* @endcode
* - long: (optional) Whether the passed-in filter tips contain extended
* explanations, i.e. intended to be output on the path 'filter/tips'
* (TRUE), or are in a short format, i.e. suitable to be displayed below a
* form element. Defaults to FALSE.
*/
function template_preprocess_filter_tips(&$variables) {
$tips = $variables['tips'];
$long = $variables['long'];
foreach ($variables['tips'] as $name => $tiplist) {
foreach ($tiplist as $tip_key => $tip) {
$tiplist[$tip_key]['attributes'] = new Attribute(array());
if ($long) {
$tiplist[$tip_key]['attributes']['class'] = array('filter-' . str_replace("/", "-", $tip['id']));
}
}
$attributes = array(
'class' => array(
'filter-type',
'filter-' . drupal_html_class($name),
),
);
$variables['tips'][$name] = array(
'attributes' => new Attribute($attributes),
'name' => String::checkPlain($name),
'list' => $tiplist,
);
}
$variables['multiple'] = count($tips) > 1;
Neil Drumm
committed
}
* @defgroup standard_filters Standard filters
Jennifer Hodgdon
committed
* Filters implemented by the Filter module.
Jennifer Hodgdon
committed
* Provides filtering of input into accepted HTML.
Dries Buytaert
committed
function _filter_html($text, $filter) {
$allowed_tags = preg_split('/\s+|<|>/', $filter->settings['allowed_html'], -1, PREG_SPLIT_NO_EMPTY);
Angie Byron
committed
$text = Xss::filter($text, $allowed_tags);
Dries Buytaert
committed
if ($filter->settings['filter_html_nofollow']) {
Alex Pott
committed
$html_dom = Html::load($text);
$links = $html_dom->getElementsByTagName('a');
Dries Buytaert
committed
foreach ($links as $link) {
$link->setAttribute('rel', 'nofollow');
}
Alex Pott
committed
$text = Html::serialize($html_dom);
Jennifer Hodgdon
committed
* Converts text into hyperlinks automatically.
*
* This filter identifies and makes clickable three types of "links".
* - URLs like http://example.com.
* - E-mail addresses like name@example.com.
Jennifer Hodgdon
committed
* - Web addresses without the "http://" protocol defined, like
* www.example.com.
* Each type must be processed separately, as there is no one regular
* expression that could possibly match all of the cases in one pass.
Dries Buytaert
committed
function _filter_url($text, $filter) {
// Tags to skip and not recurse into.
$ignore_tags = 'a|script|style|code|pre';
// Pass length to regexp callback.
Dries Buytaert
committed
_filter_url_trim(NULL, $filter->settings['filter_url_length']);
// Create an array which contains the regexps for each type of link.
// The key to the regexp is the name of a function that is used as
// callback function to process matches of the regexp. The callback function
// is to return the replacement for the match. The array is used and
// matching/replacement done below inside some loops.
$tasks = array();
// Prepare protocols pattern for absolute URLs.
// check_url() will replace any bad protocols with HTTP, so we need to support
// the identical list. While '//' is technically optional for MAILTO only,
// we cannot cleanly differ between protocols here without hard-coding MAILTO,
// so '//' is optional for all protocols.
Angie Byron
committed
// @see \Drupal\Component\Utility\UrlHelper::filterBadProtocol()
$protocols = \Drupal::config('system.filter')->get('protocols');
$protocols = implode(':(?://)?|', $protocols) . ':(?://)?';
$valid_url_path_characters = "[\p{L}\p{M}\p{N}!\*\';:=\+,\.\$\/%#\[\]\-_~@&]";
// Allow URL paths to contain balanced parens
// 1. Used in Wikipedia URLs like /Primer_(film)
// 2. Used in IIS sessions like /S(dfd346)/
$valid_url_balanced_parens = '\('. $valid_url_path_characters . '+\)';
// Valid end-of-path chracters (so /foo. does not gobble the period).
// 1. Allow =&# for empty URL parameters and other URL-join artifacts
$valid_url_ending_characters = '[\p{L}\p{M}\p{N}:_+~#=/]|(?:' . $valid_url_balanced_parens . ')';
$valid_url_query_chars = '[a-z0-9!?\*\'@\(\);:&=\+\$\/%#\[\]\-_\.,~|]';
$valid_url_query_ending_chars = '[a-z0-9_&=#\/]';
//full path
//and allow @ in a url, but only in the middle. Catch things like http://example.com/@user/
$valid_url_path = '(?:(?:'.$valid_url_path_characters . '*(?:'.$valid_url_balanced_parens .$valid_url_path_characters . '*)*'. $valid_url_ending_characters . ')|(?:@' . $valid_url_path_characters . '+\/))';
// Prepare domain name pattern.
// The ICANN seems to be on track towards accepting more diverse top level
// domains, so this pattern has been "future-proofed" to allow for TLDs
// of length 2-64.
$domain = '(?:[\p{L}\p{M}\p{N}._+-]+\.)?[\p{L}\p{M}]{2,64}\b';
$ip = '(?:[0-9]{1,3}\.){3}[0-9]{1,3}';
$auth = '[\p{L}\p{M}\p{N}:%_+*~#?&=.,/;-]+@';
$trail = '('.$valid_url_path.'*)?(\\?'.$valid_url_query_chars .'*'.$valid_url_query_ending_chars.')?';
// Match absolute URLs.
$url_pattern = "(?:$auth)?(?:$domain|$ip)/?(?:$trail)?";
$pattern = "`((?:$protocols)(?:$url_pattern))`u";
$tasks['_filter_url_parse_full_links'] = $pattern;
// Match e-mail addresses.
$url_pattern = "[\p{L}\p{M}\p{N}._-]{1,254}@(?:$domain)";
$pattern = "`($url_pattern)`u";
$tasks['_filter_url_parse_email_links'] = $pattern;
// Match www domains.
$url_pattern = "www\.(?:$domain)/?(?:$trail)?";
$pattern = "`($url_pattern)`u";
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
$tasks['_filter_url_parse_partial_links'] = $pattern;
// Each type of URL needs to be processed separately. The text is joined and
// re-split after each task, since all injected HTML tags must be correctly
// protected before the next task.
foreach ($tasks as $task => $pattern) {
// HTML comments need to be handled separately, as they may contain HTML
// markup, especially a '>'. Therefore, remove all comment contents and add
// them back later.
_filter_url_escape_comments('', TRUE);
$text = preg_replace_callback('`<!--(.*?)-->`s', '_filter_url_escape_comments', $text);
// Split at all tags; ensures that no tags or attributes are processed.
$chunks = preg_split('/(<.+?>)/is', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
// PHP ensures that the array consists of alternating delimiters and
// literals, and begins and ends with a literal (inserting NULL as
// required). Therefore, the first chunk is always text:
$chunk_type = 'text';
// If a tag of $ignore_tags is found, it is stored in $open_tag and only
// removed when the closing tag is found. Until the closing tag is found,
// no replacements are made.
$open_tag = '';
for ($i = 0; $i < count($chunks); $i++) {
if ($chunk_type == 'text') {
// Only process this text if there are no unclosed $ignore_tags.
if ($open_tag == '') {
// If there is a match, inject a link into this chunk via the callback
// function contained in $task.
$chunks[$i] = preg_replace_callback($pattern, $task, $chunks[$i]);
}
// Text chunk is done, so next chunk must be a tag.
$chunk_type = 'tag';
}
else {
// Only process this tag if there are no unclosed $ignore_tags.
if ($open_tag == '') {
// Check whether this tag is contained in $ignore_tags.
if (preg_match("`<($ignore_tags)(?:\s|>)`i", $chunks[$i], $matches)) {
$open_tag = $matches[1];
}
}
// Otherwise, check whether this is the closing tag for $open_tag.
else {
if (preg_match("`<\/$open_tag>`i", $chunks[$i], $matches)) {
$open_tag = '';
}
}
// Tag chunk is done, so next chunk must be text.
$chunk_type = 'text';
}
}
$text = implode($chunks);
// Revert back to the original comment contents
_filter_url_escape_comments('', FALSE);
$text = preg_replace_callback('`<!--(.*?)-->`', '_filter_url_escape_comments', $text);
}
return $text;
}
/**
Jennifer Hodgdon
committed
* Makes links out of absolute URLs.
*
* Callback for preg_replace_callback() within _filter_url().
*/
function _filter_url_parse_full_links($match) {
// The $i:th parenthesis in the regexp contains the URL.
$i = 1;
$match[$i] = decode_entities($match[$i]);
$caption = check_plain(_filter_url_trim($match[$i]));
$match[$i] = check_plain($match[$i]);
return '<a href="' . $match[$i] . '">' . $caption . '</a>';
}
/**
Jennifer Hodgdon
committed
* Makes links out of e-mail addresses.
*
* Callback for preg_replace_callback() within _filter_url().
*/
function _filter_url_parse_email_links($match) {
// The $i:th parenthesis in the regexp contains the URL.
$i = 0;
$match[$i] = decode_entities($match[$i]);
$caption = check_plain(_filter_url_trim($match[$i]));
$match[$i] = check_plain($match[$i]);
return '<a href="mailto:' . $match[$i] . '">' . $caption . '</a>';
Jennifer Hodgdon
committed
* Makes links out of domain names starting with "www."
*
* Callback for preg_replace_callback() within _filter_url().
*/
function _filter_url_parse_partial_links($match) {
// The $i:th parenthesis in the regexp contains the URL.
$i = 1;
$match[$i] = decode_entities($match[$i]);
$caption = check_plain(_filter_url_trim($match[$i]));
$match[$i] = check_plain($match[$i]);
return '<a href="http://' . $match[$i] . '">' . $caption . '</a>';
}
/**
Jennifer Hodgdon
committed
* Escapes the contents of HTML comments.
*
* Callback for preg_replace_callback() within _filter_url().
*
* @param $match
* An array containing matches to replace from preg_replace_callback(),
* whereas $match[1] is expected to contain the content to be filtered.
* @param $escape
Jennifer Hodgdon
committed
* (optional) A Boolean indicating whether to escape (TRUE) or unescape
* comments (FALSE). Defaults to NULL, indicating neither. If TRUE, statically
* cached $comments are reset.
*/
function _filter_url_escape_comments($match, $escape = NULL) {
static $mode, $comments = array();
if (isset($escape)) {
$mode = $escape;
if ($escape){
$comments = array();
}
return;
}
// Replace all HTML coments with a '<!-- [hash] -->' placeholder.
if ($mode) {
$content = $match[1];
Angie Byron
committed
$hash = hash('sha256', $content);
$comments[$hash] = $content;
return "<!-- $hash -->";
}
// Or replace placeholders with actual comment contents.
else {
$hash = $match[1];
$hash = trim($hash);
$content = $comments[$hash];
return "<!--$content-->";
}
}
/**
* Shortens long URLs to http://www.example.com/long/url...
*/
function _filter_url_trim($text, $length = NULL) {
static $_length;
if ($length !== NULL) {
$_length = $length;
}
// Use +3 for '...' string length.
if ($_length && strlen($text) > $_length + 3) {