3 namespace Drupal\filter\Entity;
5 use Drupal\Component\Plugin\PluginInspectionInterface;
6 use Drupal\Core\Config\Entity\ConfigEntityBase;
7 use Drupal\Core\Entity\EntityWithPluginCollectionInterface;
8 use Drupal\Core\Entity\EntityStorageInterface;
9 use Drupal\filter\FilterFormatInterface;
10 use Drupal\filter\FilterPluginCollection;
11 use Drupal\filter\Plugin\FilterInterface;
14 * Represents a text format.
17 * id = "filter_format",
18 * label = @Translation("Text format"),
21 * "add" = "Drupal\filter\FilterFormatAddForm",
22 * "edit" = "Drupal\filter\FilterFormatEditForm",
23 * "disable" = "Drupal\filter\Form\FilterDisableForm"
25 * "list_builder" = "Drupal\filter\FilterFormatListBuilder",
26 * "access" = "Drupal\filter\FilterFormatAccessControlHandler",
28 * config_prefix = "format",
29 * admin_permission = "administer filters",
33 * "weight" = "weight",
37 * "edit-form" = "/admin/config/content/formats/manage/{filter_format}",
38 * "disable" = "/admin/config/content/formats/manage/{filter_format}/disable"
49 class FilterFormat extends ConfigEntityBase implements FilterFormatInterface, EntityWithPluginCollectionInterface {
52 * Unique machine name of the format.
54 * @todo Rename to $id.
61 * Unique label of the text format.
63 * Since text formats impact a site's security, two formats with the same
64 * label but different filter configuration would impose a security risk.
65 * Therefore, each text format label must be unique.
67 * @todo Rename to $label.
74 * Weight of this format in the text format selector.
76 * The first/lowest text format that is accessible for a user is used as
81 protected $weight = 0;
84 * List of user role IDs to grant access to use this format on initial creation.
86 * This property is always empty and unused for existing text formats.
88 * Default configuration objects of modules and installation profiles are
89 * allowed to specify a list of user role IDs to grant access to.
91 * This property only has an effect when a new text format is created and the
92 * list is not empty. By default, no user role is allowed to use a new format.
99 * Configured filters for this text format.
101 * An associative array of filters assigned to the text format, keyed by the
102 * instance ID of each filter and using the properties:
103 * - id: The plugin ID of the filter plugin instance.
104 * - provider: The name of the provider that owns the filter.
105 * - status: (optional) A Boolean indicating whether the filter is
106 * enabled in the text format. Defaults to FALSE.
107 * - weight: (optional) The weight of the filter in the text format. Defaults
109 * - settings: (optional) An array of configured settings for the filter.
111 * Use FilterFormat::filters() to access the actual filters.
115 protected $filters = [];
118 * Holds the collection of filters that are attached to this format.
120 * @var \Drupal\filter\FilterPluginCollection
122 protected $filterCollection;
127 public function id() {
128 return $this->format;
134 public function filters($instance_id = NULL) {
135 if (!isset($this->filterCollection)) {
136 $this->filterCollection = new FilterPluginCollection(\Drupal::service('plugin.manager.filter'), $this->filters);
137 $this->filterCollection->sort();
139 if (isset($instance_id)) {
140 return $this->filterCollection->get($instance_id);
142 return $this->filterCollection;
148 public function getPluginCollections() {
149 return ['filters' => $this->filters()];
155 public function setFilterConfig($instance_id, array $configuration) {
156 $this->filters[$instance_id] = $configuration;
157 if (isset($this->filterCollection)) {
158 $this->filterCollection->setInstanceConfiguration($instance_id, $configuration);
166 public function toArray() {
167 $properties = parent::toArray();
168 // The 'roles' property is only used during install and should never
169 // actually be saved.
170 unset($properties['roles']);
177 public function disable() {
178 if ($this->isFallbackFormat()) {
179 throw new \LogicException("The fallback text format '{$this->id()}' cannot be disabled.");
184 // Allow modules to react on text format deletion.
185 \Drupal::moduleHandler()->invokeAll('filter_format_disable', [$this]);
187 // Clear the filter cache whenever a text format is disabled.
188 filter_formats_reset();
196 public function preSave(EntityStorageInterface $storage) {
197 // Ensure the filters have been sorted before saving.
198 $this->filters()->sort();
200 parent::preSave($storage);
202 $this->name = trim($this->label());
208 public function postSave(EntityStorageInterface $storage, $update = TRUE) {
209 parent::postSave($storage, $update);
211 // Clear the static caches of filter_formats() and others.
212 filter_formats_reset();
214 if (!$update && !$this->isSyncing()) {
215 // Default configuration of modules and installation profiles is allowed
216 // to specify a list of user roles to grant access to for the new format;
217 // apply the defined user role permissions when a new format is inserted
218 // and has a non-empty $roles property.
219 // Note: user_role_change_permissions() triggers a call chain back into
220 // \Drupal\filter\FilterPermissions::permissions() and lastly
221 // filter_formats(), so its cache must be reset upfront.
222 if (($roles = $this->get('roles')) && $permission = $this->getPermissionName()) {
223 foreach (user_roles() as $rid => $name) {
224 $enabled = in_array($rid, $roles, TRUE);
225 user_role_change_permissions($rid, [$permission => $enabled]);
232 * Returns if this format is the fallback format.
234 * The fallback format can never be disabled. It must always be available.
237 * TRUE if this format is the fallback format, FALSE otherwise.
239 public function isFallbackFormat() {
240 $fallback_format = \Drupal::config('filter.settings')->get('fallback_format');
241 return $this->id() == $fallback_format;
247 public function getPermissionName() {
248 return !$this->isFallbackFormat() ? 'use text format ' . $this->id() : FALSE;
254 public function getFilterTypes() {
257 $filters = $this->filters();
258 foreach ($filters as $filter) {
259 if ($filter->status) {
260 $filter_types[] = $filter->getType();
264 return array_unique($filter_types);
270 public function getHtmlRestrictions() {
271 // Ignore filters that are disabled or don't have HTML restrictions.
272 $filters = array_filter($this->filters()->getAll(), function($filter) {
273 if (!$filter->status) {
276 if ($filter->getType() === FilterInterface::TYPE_HTML_RESTRICTOR && $filter->getHTMLRestrictions() !== FALSE) {
282 if (empty($filters)) {
286 // From the set of remaining filters (they were filtered by array_filter()
287 // above), collect the list of tags and attributes that are allowed by all
288 // filters, i.e. the intersection of all allowed tags and attributes.
289 $restrictions = array_reduce($filters, function($restrictions, $filter) {
290 $new_restrictions = $filter->getHTMLRestrictions();
292 // The first filter with HTML restrictions provides the initial set.
293 if (!isset($restrictions)) {
294 return $new_restrictions;
296 // Subsequent filters with an "allowed html" setting must be intersected
297 // with the existing set, to ensure we only end up with the tags that are
298 // allowed by *all* filters with an "allowed html" setting.
300 // Track the union of forbidden (blacklisted) tags.
301 if (isset($new_restrictions['forbidden_tags'])) {
302 if (!isset($restrictions['forbidden_tags'])) {
303 $restrictions['forbidden_tags'] = $new_restrictions['forbidden_tags'];
306 $restrictions['forbidden_tags'] = array_unique(array_merge($restrictions['forbidden_tags'], $new_restrictions['forbidden_tags']));
310 // Track the intersection of allowed (whitelisted) tags.
311 if (isset($restrictions['allowed'])) {
312 $intersection = $restrictions['allowed'];
313 foreach ($intersection as $tag => $attributes) {
314 // If the current tag is not whitelisted by the new filter, then
315 // it's outside of the intersection.
316 if (!array_key_exists($tag, $new_restrictions['allowed'])) {
317 // The exception is the asterisk (which applies to all tags): it
318 // does not need to be whitelisted by every filter in order to be
319 // used; not every filter needs attribute restrictions on all tags.
323 unset($intersection[$tag]);
325 // The tag is in the intersection, but now we must calculate the
326 // intersection of the allowed attributes.
328 $current_attributes = $intersection[$tag];
329 $new_attributes = $new_restrictions['allowed'][$tag];
330 // The current intersection does not allow any attributes, never
332 if (!is_array($current_attributes) && $current_attributes == FALSE) {
335 // The new filter allows less attributes (all -> list or none).
336 elseif (!is_array($current_attributes) && $current_attributes == TRUE && ($new_attributes == FALSE || is_array($new_attributes))) {
337 $intersection[$tag] = $new_attributes;
339 // The new filter allows less attributes (list -> none).
340 elseif (is_array($current_attributes) && $new_attributes == FALSE) {
341 $intersection[$tag] = $new_attributes;
343 // The new filter allows more attributes; retain current.
344 elseif (is_array($current_attributes) && $new_attributes == TRUE) {
347 // The new filter allows the same attributes; retain current.
348 elseif ($current_attributes == $new_attributes) {
351 // Both list an array of attribute values; do an intersection,
352 // where we take into account that a value of:
353 // - TRUE means the attribute value is allowed;
354 // - FALSE means the attribute value is forbidden;
355 // hence we keep the ANDed result.
357 $intersection[$tag] = array_intersect_key($intersection[$tag], $new_attributes);
358 foreach (array_keys($intersection[$tag]) as $attribute_value) {
359 $intersection[$tag][$attribute_value] = $intersection[$tag][$attribute_value] && $new_attributes[$attribute_value];
364 $restrictions['allowed'] = $intersection;
367 return $restrictions;
371 // Simplification: if we have both a (intersected) whitelist and a (unioned)
372 // blacklist, then remove any tags from the whitelist that also exist in the
373 // blacklist. Now the whitelist alone expresses all tag-level restrictions,
374 // and we can delete the blacklist.
375 if (isset($restrictions['allowed']) && isset($restrictions['forbidden_tags'])) {
376 foreach ($restrictions['forbidden_tags'] as $tag) {
377 if (isset($restrictions['allowed'][$tag])) {
378 unset($restrictions['allowed'][$tag]);
381 unset($restrictions['forbidden_tags']);
384 // Simplification: if the only remaining allowed tag is the asterisk (which
385 // contains attribute restrictions that apply to all tags), and only
386 // whitelisting filters were used, then effectively nothing is allowed.
387 if (isset($restrictions['allowed'])) {
388 if (count($restrictions['allowed']) === 1 && array_key_exists('*', $restrictions['allowed']) && !isset($restrictions['forbidden_tags'])) {
389 $restrictions['allowed'] = [];
393 return $restrictions;
400 public function removeFilter($instance_id) {
401 unset($this->filters[$instance_id]);
402 $this->filterCollection->removeInstanceId($instance_id);
408 public function onDependencyRemoval(array $dependencies) {
409 $changed = parent::onDependencyRemoval($dependencies);
410 $filters = $this->filters();
411 foreach ($filters as $filter) {
412 // Remove disabled filters, so that this FilterFormat config entity can
413 // continue to exist.
414 if (!$filter->status && in_array($filter->provider, $dependencies['module'])) {
415 $this->removeFilter($filter->getPluginId());
425 protected function calculatePluginDependencies(PluginInspectionInterface $instance) {
426 // Only add dependencies for plugins that are actually configured. This is
427 // necessary because the filter plugin collection will return all available
429 // @see \Drupal\filter\FilterPluginCollection::getConfiguration()
430 if (isset($this->filters[$instance->getPluginId()])) {
431 parent::calculatePluginDependencies($instance);