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"),
19 * label_collection = @Translation("Text formats"),
20 * label_singular = @Translation("text format"),
21 * label_plural = @Translation("text formats"),
22 * label_count = @PluralTranslation(
23 * singular = "@count text format",
24 * plural = "@count text formats",
28 * "add" = "Drupal\filter\FilterFormatAddForm",
29 * "edit" = "Drupal\filter\FilterFormatEditForm",
30 * "disable" = "Drupal\filter\Form\FilterDisableForm"
32 * "list_builder" = "Drupal\filter\FilterFormatListBuilder",
33 * "access" = "Drupal\filter\FilterFormatAccessControlHandler",
35 * config_prefix = "format",
36 * admin_permission = "administer filters",
40 * "weight" = "weight",
44 * "edit-form" = "/admin/config/content/formats/manage/{filter_format}",
45 * "disable" = "/admin/config/content/formats/manage/{filter_format}/disable"
56 class FilterFormat extends ConfigEntityBase implements FilterFormatInterface, EntityWithPluginCollectionInterface {
59 * Unique machine name of the format.
61 * @todo Rename to $id.
68 * Unique label of the text format.
70 * Since text formats impact a site's security, two formats with the same
71 * label but different filter configuration would impose a security risk.
72 * Therefore, each text format label must be unique.
74 * @todo Rename to $label.
81 * Weight of this format in the text format selector.
83 * The first/lowest text format that is accessible for a user is used as
88 protected $weight = 0;
91 * List of user role IDs to grant access to use this format on initial creation.
93 * This property is always empty and unused for existing text formats.
95 * Default configuration objects of modules and installation profiles are
96 * allowed to specify a list of user role IDs to grant access to.
98 * This property only has an effect when a new text format is created and the
99 * list is not empty. By default, no user role is allowed to use a new format.
106 * Configured filters for this text format.
108 * An associative array of filters assigned to the text format, keyed by the
109 * instance ID of each filter and using the properties:
110 * - id: The plugin ID of the filter plugin instance.
111 * - provider: The name of the provider that owns the filter.
112 * - status: (optional) A Boolean indicating whether the filter is
113 * enabled in the text format. Defaults to FALSE.
114 * - weight: (optional) The weight of the filter in the text format. Defaults
116 * - settings: (optional) An array of configured settings for the filter.
118 * Use FilterFormat::filters() to access the actual filters.
122 protected $filters = [];
125 * Holds the collection of filters that are attached to this format.
127 * @var \Drupal\filter\FilterPluginCollection
129 protected $filterCollection;
134 public function id() {
135 return $this->format;
141 public function filters($instance_id = NULL) {
142 if (!isset($this->filterCollection)) {
143 $this->filterCollection = new FilterPluginCollection(\Drupal::service('plugin.manager.filter'), $this->filters);
144 $this->filterCollection->sort();
146 if (isset($instance_id)) {
147 return $this->filterCollection->get($instance_id);
149 return $this->filterCollection;
155 public function getPluginCollections() {
156 return ['filters' => $this->filters()];
162 public function setFilterConfig($instance_id, array $configuration) {
163 $this->filters[$instance_id] = $configuration;
164 if (isset($this->filterCollection)) {
165 $this->filterCollection->setInstanceConfiguration($instance_id, $configuration);
173 public function toArray() {
174 $properties = parent::toArray();
175 // The 'roles' property is only used during install and should never
176 // actually be saved.
177 unset($properties['roles']);
184 public function disable() {
185 if ($this->isFallbackFormat()) {
186 throw new \LogicException("The fallback text format '{$this->id()}' cannot be disabled.");
191 // Allow modules to react on text format deletion.
192 \Drupal::moduleHandler()->invokeAll('filter_format_disable', [$this]);
194 // Clear the filter cache whenever a text format is disabled.
195 filter_formats_reset();
203 public function preSave(EntityStorageInterface $storage) {
204 // Ensure the filters have been sorted before saving.
205 $this->filters()->sort();
207 parent::preSave($storage);
209 $this->name = trim($this->label());
215 public function postSave(EntityStorageInterface $storage, $update = TRUE) {
216 parent::postSave($storage, $update);
218 // Clear the static caches of filter_formats() and others.
219 filter_formats_reset();
221 if (!$update && !$this->isSyncing()) {
222 // Default configuration of modules and installation profiles is allowed
223 // to specify a list of user roles to grant access to for the new format;
224 // apply the defined user role permissions when a new format is inserted
225 // and has a non-empty $roles property.
226 // Note: user_role_change_permissions() triggers a call chain back into
227 // \Drupal\filter\FilterPermissions::permissions() and lastly
228 // filter_formats(), so its cache must be reset upfront.
229 if (($roles = $this->get('roles')) && $permission = $this->getPermissionName()) {
230 foreach (user_roles() as $rid => $name) {
231 $enabled = in_array($rid, $roles, TRUE);
232 user_role_change_permissions($rid, [$permission => $enabled]);
239 * Returns if this format is the fallback format.
241 * The fallback format can never be disabled. It must always be available.
244 * TRUE if this format is the fallback format, FALSE otherwise.
246 public function isFallbackFormat() {
247 $fallback_format = \Drupal::config('filter.settings')->get('fallback_format');
248 return $this->id() == $fallback_format;
254 public function getPermissionName() {
255 return !$this->isFallbackFormat() ? 'use text format ' . $this->id() : FALSE;
261 public function getFilterTypes() {
264 $filters = $this->filters();
265 foreach ($filters as $filter) {
266 if ($filter->status) {
267 $filter_types[] = $filter->getType();
271 return array_unique($filter_types);
277 public function getHtmlRestrictions() {
278 // Ignore filters that are disabled or don't have HTML restrictions.
279 $filters = array_filter($this->filters()->getAll(), function ($filter) {
280 if (!$filter->status) {
283 if ($filter->getType() === FilterInterface::TYPE_HTML_RESTRICTOR && $filter->getHTMLRestrictions() !== FALSE) {
289 if (empty($filters)) {
293 // From the set of remaining filters (they were filtered by array_filter()
294 // above), collect the list of tags and attributes that are allowed by all
295 // filters, i.e. the intersection of all allowed tags and attributes.
296 $restrictions = array_reduce($filters, function ($restrictions, $filter) {
297 $new_restrictions = $filter->getHTMLRestrictions();
299 // The first filter with HTML restrictions provides the initial set.
300 if (!isset($restrictions)) {
301 return $new_restrictions;
303 // Subsequent filters with an "allowed html" setting must be intersected
304 // with the existing set, to ensure we only end up with the tags that are
305 // allowed by *all* filters with an "allowed html" setting.
307 // Track the union of forbidden (blacklisted) tags.
308 if (isset($new_restrictions['forbidden_tags'])) {
309 if (!isset($restrictions['forbidden_tags'])) {
310 $restrictions['forbidden_tags'] = $new_restrictions['forbidden_tags'];
313 $restrictions['forbidden_tags'] = array_unique(array_merge($restrictions['forbidden_tags'], $new_restrictions['forbidden_tags']));
317 // Track the intersection of allowed (whitelisted) tags.
318 if (isset($restrictions['allowed'])) {
319 $intersection = $restrictions['allowed'];
320 foreach ($intersection as $tag => $attributes) {
321 // If the current tag is not whitelisted by the new filter, then
322 // it's outside of the intersection.
323 if (!array_key_exists($tag, $new_restrictions['allowed'])) {
324 // The exception is the asterisk (which applies to all tags): it
325 // does not need to be whitelisted by every filter in order to be
326 // used; not every filter needs attribute restrictions on all tags.
330 unset($intersection[$tag]);
332 // The tag is in the intersection, but now we must calculate the
333 // intersection of the allowed attributes.
335 $current_attributes = $intersection[$tag];
336 $new_attributes = $new_restrictions['allowed'][$tag];
337 // The current intersection does not allow any attributes, never
339 if (!is_array($current_attributes) && $current_attributes == FALSE) {
342 // The new filter allows less attributes (all -> list or none).
343 elseif (!is_array($current_attributes) && $current_attributes == TRUE && ($new_attributes == FALSE || is_array($new_attributes))) {
344 $intersection[$tag] = $new_attributes;
346 // The new filter allows less attributes (list -> none).
347 elseif (is_array($current_attributes) && $new_attributes == FALSE) {
348 $intersection[$tag] = $new_attributes;
350 // The new filter allows more attributes; retain current.
351 elseif (is_array($current_attributes) && $new_attributes == TRUE) {
354 // The new filter allows the same attributes; retain current.
355 elseif ($current_attributes == $new_attributes) {
358 // Both list an array of attribute values; do an intersection,
359 // where we take into account that a value of:
360 // - TRUE means the attribute value is allowed;
361 // - FALSE means the attribute value is forbidden;
362 // hence we keep the ANDed result.
364 $intersection[$tag] = array_intersect_key($intersection[$tag], $new_attributes);
365 foreach (array_keys($intersection[$tag]) as $attribute_value) {
366 $intersection[$tag][$attribute_value] = $intersection[$tag][$attribute_value] && $new_attributes[$attribute_value];
371 $restrictions['allowed'] = $intersection;
374 return $restrictions;
378 // Simplification: if we have both a (intersected) whitelist and a (unioned)
379 // blacklist, then remove any tags from the whitelist that also exist in the
380 // blacklist. Now the whitelist alone expresses all tag-level restrictions,
381 // and we can delete the blacklist.
382 if (isset($restrictions['allowed']) && isset($restrictions['forbidden_tags'])) {
383 foreach ($restrictions['forbidden_tags'] as $tag) {
384 if (isset($restrictions['allowed'][$tag])) {
385 unset($restrictions['allowed'][$tag]);
388 unset($restrictions['forbidden_tags']);
391 // Simplification: if the only remaining allowed tag is the asterisk (which
392 // contains attribute restrictions that apply to all tags), and only
393 // whitelisting filters were used, then effectively nothing is allowed.
394 if (isset($restrictions['allowed'])) {
395 if (count($restrictions['allowed']) === 1 && array_key_exists('*', $restrictions['allowed']) && !isset($restrictions['forbidden_tags'])) {
396 $restrictions['allowed'] = [];
400 return $restrictions;
407 public function removeFilter($instance_id) {
408 unset($this->filters[$instance_id]);
409 $this->filterCollection->removeInstanceId($instance_id);
415 public function onDependencyRemoval(array $dependencies) {
416 $changed = parent::onDependencyRemoval($dependencies);
417 $filters = $this->filters();
418 foreach ($filters as $filter) {
419 // Remove disabled filters, so that this FilterFormat config entity can
420 // continue to exist.
421 if (!$filter->status && in_array($filter->provider, $dependencies['module'])) {
422 $this->removeFilter($filter->getPluginId());
432 protected function calculatePluginDependencies(PluginInspectionInterface $instance) {
433 // Only add dependencies for plugins that are actually configured. This is
434 // necessary because the filter plugin collection will return all available
436 // @see \Drupal\filter\FilterPluginCollection::getConfiguration()
437 if (isset($this->filters[$instance->getPluginId()])) {
438 parent::calculatePluginDependencies($instance);