9dbaa62fd2c21d341fd3df433a039b65511d9ef2
[yaffs-website] / web / core / modules / filter / src / Entity / FilterFormat.php
1 <?php
2
3 namespace Drupal\filter\Entity;
4
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;
12
13 /**
14  * Represents a text format.
15  *
16  * @ConfigEntityType(
17  *   id = "filter_format",
18  *   label = @Translation("Text format"),
19  *   handlers = {
20  *     "form" = {
21  *       "add" = "Drupal\filter\FilterFormatAddForm",
22  *       "edit" = "Drupal\filter\FilterFormatEditForm",
23  *       "disable" = "Drupal\filter\Form\FilterDisableForm"
24  *     },
25  *     "list_builder" = "Drupal\filter\FilterFormatListBuilder",
26  *     "access" = "Drupal\filter\FilterFormatAccessControlHandler",
27  *   },
28  *   config_prefix = "format",
29  *   admin_permission = "administer filters",
30  *   entity_keys = {
31  *     "id" = "format",
32  *     "label" = "name",
33  *     "weight" = "weight",
34  *     "status" = "status"
35  *   },
36  *   links = {
37  *     "edit-form" = "/admin/config/content/formats/manage/{filter_format}",
38  *     "disable" = "/admin/config/content/formats/manage/{filter_format}/disable"
39  *   },
40  *   config_export = {
41  *     "name",
42  *     "format",
43  *     "weight",
44  *     "roles",
45  *     "filters",
46  *   }
47  * )
48  */
49 class FilterFormat extends ConfigEntityBase implements FilterFormatInterface, EntityWithPluginCollectionInterface {
50
51   /**
52    * Unique machine name of the format.
53    *
54    * @todo Rename to $id.
55    *
56    * @var string
57    */
58   protected $format;
59
60   /**
61    * Unique label of the text format.
62    *
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.
66    *
67    * @todo Rename to $label.
68    *
69    * @var string
70    */
71   protected $name;
72
73   /**
74    * Weight of this format in the text format selector.
75    *
76    * The first/lowest text format that is accessible for a user is used as
77    * default format.
78    *
79    * @var int
80    */
81   protected $weight = 0;
82
83   /**
84    * List of user role IDs to grant access to use this format on initial creation.
85    *
86    * This property is always empty and unused for existing text formats.
87    *
88    * Default configuration objects of modules and installation profiles are
89    * allowed to specify a list of user role IDs to grant access to.
90    *
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.
93    *
94    * @var array
95    */
96   protected $roles;
97
98   /**
99    * Configured filters for this text format.
100    *
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
108    *   to 0.
109    * - settings: (optional) An array of configured settings for the filter.
110    *
111    * Use FilterFormat::filters() to access the actual filters.
112    *
113    * @var array
114    */
115   protected $filters = [];
116
117   /**
118    * Holds the collection of filters that are attached to this format.
119    *
120    * @var \Drupal\filter\FilterPluginCollection
121    */
122   protected $filterCollection;
123
124   /**
125    * {@inheritdoc}
126    */
127   public function id() {
128     return $this->format;
129   }
130
131   /**
132    * {@inheritdoc}
133    */
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();
138     }
139     if (isset($instance_id)) {
140       return $this->filterCollection->get($instance_id);
141     }
142     return $this->filterCollection;
143   }
144
145   /**
146    * {@inheritdoc}
147    */
148   public function getPluginCollections() {
149     return ['filters' => $this->filters()];
150   }
151
152   /**
153    * {@inheritdoc}
154    */
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);
159     }
160     return $this;
161   }
162
163   /**
164    * {@inheritdoc}
165    */
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']);
171     return $properties;
172   }
173
174   /**
175    * {@inheritdoc}
176    */
177   public function disable() {
178     if ($this->isFallbackFormat()) {
179       throw new \LogicException("The fallback text format '{$this->id()}' cannot be disabled.");
180     }
181
182     parent::disable();
183
184     // Allow modules to react on text format deletion.
185     \Drupal::moduleHandler()->invokeAll('filter_format_disable', [$this]);
186
187     // Clear the filter cache whenever a text format is disabled.
188     filter_formats_reset();
189
190     return $this;
191   }
192
193   /**
194    * {@inheritdoc}
195    */
196   public function preSave(EntityStorageInterface $storage) {
197     // Ensure the filters have been sorted before saving.
198     $this->filters()->sort();
199
200     parent::preSave($storage);
201
202     $this->name = trim($this->label());
203   }
204
205   /**
206    * {@inheritdoc}
207    */
208   public function postSave(EntityStorageInterface $storage, $update = TRUE) {
209     parent::postSave($storage, $update);
210
211     // Clear the static caches of filter_formats() and others.
212     filter_formats_reset();
213
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]);
226         }
227       }
228     }
229   }
230
231   /**
232    * Returns if this format is the fallback format.
233    *
234    * The fallback format can never be disabled. It must always be available.
235    *
236    * @return bool
237    *   TRUE if this format is the fallback format, FALSE otherwise.
238    */
239   public function isFallbackFormat() {
240     $fallback_format = \Drupal::config('filter.settings')->get('fallback_format');
241     return $this->id() == $fallback_format;
242   }
243
244   /**
245    * {@inheritdoc}
246    */
247   public function getPermissionName() {
248     return !$this->isFallbackFormat() ? 'use text format ' . $this->id() : FALSE;
249   }
250
251   /**
252    * {@inheritdoc}
253    */
254   public function getFilterTypes() {
255     $filter_types = [];
256
257     $filters = $this->filters();
258     foreach ($filters as $filter) {
259       if ($filter->status) {
260         $filter_types[] = $filter->getType();
261       }
262     }
263
264     return array_unique($filter_types);
265   }
266
267   /**
268    * {@inheritdoc}
269    */
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) {
274         return FALSE;
275       }
276       if ($filter->getType() === FilterInterface::TYPE_HTML_RESTRICTOR && $filter->getHTMLRestrictions() !== FALSE) {
277         return TRUE;
278       }
279       return FALSE;
280     });
281
282     if (empty($filters)) {
283       return FALSE;
284     }
285     else {
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();
291
292         // The first filter with HTML restrictions provides the initial set.
293         if (!isset($restrictions)) {
294           return $new_restrictions;
295         }
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.
299         else {
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'];
304             }
305             else {
306               $restrictions['forbidden_tags'] = array_unique(array_merge($restrictions['forbidden_tags'], $new_restrictions['forbidden_tags']));
307             }
308           }
309
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.
320                 if ($tag === '*') {
321                   continue;
322                 }
323                 unset($intersection[$tag]);
324               }
325               // The tag is in the intersection, but now we must calculate the
326               // intersection of the allowed attributes.
327               else {
328                 $current_attributes = $intersection[$tag];
329                 $new_attributes = $new_restrictions['allowed'][$tag];
330                 // The current intersection does not allow any attributes, never
331                 // allow.
332                 if (!is_array($current_attributes) && $current_attributes == FALSE) {
333                   continue;
334                 }
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;
338                 }
339                 // The new filter allows less attributes (list -> none).
340                 elseif (is_array($current_attributes) && $new_attributes == FALSE) {
341                   $intersection[$tag] = $new_attributes;
342                 }
343                 // The new filter allows more attributes; retain current.
344                 elseif (is_array($current_attributes) && $new_attributes == TRUE) {
345                   continue;
346                 }
347                 // The new filter allows the same attributes; retain current.
348                 elseif ($current_attributes == $new_attributes) {
349                   continue;
350                 }
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.
356                 else {
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];
360                   }
361                 }
362               }
363             }
364             $restrictions['allowed'] = $intersection;
365           }
366
367           return $restrictions;
368         }
369       }, NULL);
370
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]);
379           }
380         }
381         unset($restrictions['forbidden_tags']);
382       }
383
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'] = [];
390         }
391       }
392
393       return $restrictions;
394     }
395   }
396
397   /**
398    * {@inheritdoc}
399    */
400   public function removeFilter($instance_id) {
401     unset($this->filters[$instance_id]);
402     $this->filterCollection->removeInstanceId($instance_id);
403   }
404
405   /**
406    * {@inheritdoc}
407    */
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());
416         $changed = TRUE;
417       }
418     }
419     return $changed;
420   }
421
422   /**
423    * {@inheritdoc}
424    */
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
428     // filter plugins.
429     // @see \Drupal\filter\FilterPluginCollection::getConfiguration()
430     if (isset($this->filters[$instance->getPluginId()])) {
431       parent::calculatePluginDependencies($instance);
432     }
433   }
434
435 }