Upgraded drupal core with security updates
[yaffs-website] / web / core / modules / editor / editor.module
1 <?php
2
3 /**
4  * @file
5  * Adds bindings for client-side "text editors" to text formats.
6  */
7
8 use Drupal\Component\Utility\Html;
9 use Drupal\editor\Entity\Editor;
10 use Drupal\Core\Entity\FieldableEntityInterface;
11 use Drupal\Core\Field\FieldDefinitionInterface;
12 use Drupal\Core\Form\FormStateInterface;
13 use Drupal\Core\Render\Element;
14 use Drupal\Core\Routing\RouteMatchInterface;
15 use Drupal\Core\StringTranslation\TranslatableMarkup;
16 use Drupal\Core\Entity\EntityInterface;
17 use Drupal\filter\FilterFormatInterface;
18 use Drupal\filter\Plugin\FilterInterface;
19
20 /**
21  * Implements hook_help().
22  */
23 function editor_help($route_name, RouteMatchInterface $route_match) {
24   switch ($route_name) {
25     case 'help.page.editor':
26       $output = '';
27       $output .= '<h3>' . t('About') . '</h3>';
28       $output .= '<p>' . t('The Text Editor module provides a framework that other modules (such as <a href=":ckeditor">CKEditor module</a>) can use to provide toolbars and other functionality that allow users to format text more easily than typing HTML tags directly. For more information, see the <a href=":documentation">online documentation for the Text Editor module</a>.', [':documentation' => 'https://www.drupal.org/documentation/modules/editor', ':ckeditor' => (\Drupal::moduleHandler()->moduleExists('ckeditor')) ? \Drupal::url('help.page', ['name' => 'ckeditor']) : '#']) . '</p>';
29       $output .= '<h3>' . t('Uses') . '</h3>';
30       $output .= '<dl>';
31       $output .= '<dt>' . t('Installing text editors') . '</dt>';
32       $output .= '<dd>' . t('The Text Editor module provides a framework for managing editors. To use it, you also need to enable a text editor. This can either be the core <a href=":ckeditor">CKEditor module</a>, which can be enabled on the <a href=":extend">Extend page</a>, or a contributed module for any other text editor. When installing a contributed text editor module, be sure to check the installation instructions, because you will most likely need to download and install an external library as well as the Drupal module.', [':ckeditor' => (\Drupal::moduleHandler()->moduleExists('ckeditor')) ? \Drupal::url('help.page', ['name' => 'ckeditor']) : '#', ':extend' => \Drupal::url('system.modules_list')]) . '</dd>';
33       $output .= '<dt>' . t('Enabling a text editor for a text format') . '</dt>';
34       $output .= '<dd>' . t('On the <a href=":formats">Text formats and editors page</a> you can see which text editor is associated with each text format. You can change this by clicking on the <em>Configure</em> link, and then choosing a text editor or <em>none</em> from the <em>Text editor</em> drop-down list. The text editor will then be displayed with any text field for which this text format is chosen.', [':formats' => \Drupal::url('filter.admin_overview')]) . '</dd>';
35       $output .= '<dt>' . t('Configuring a text editor') . '</dt>';
36       $output .= '<dd>' . t('Once a text editor is associated with a text format, you can configure it by clicking on the <em>Configure</em> link for this format. Depending on the specific text editor, you can configure it for example by adding buttons to its toolbar. Typically these buttons provide formatting or editing tools, and they often insert HTML tags into the field source. For details, see the help page of the specific text editor.') . '</dd>';
37       $output .= '<dt>' . t('Using different text editors and formats') . '</dt>';
38       $output .= '<dd>' . t('If you change the text format on a text field, the text editor will change as well because the text editor configuration is associated with the individual text format. This allows the use of the same text editor with different options for different text formats. It also allows users to choose between text formats with different text editors if they are installed.') . '</dd>';
39       $output .= '</dl>';
40       return $output;
41   }
42 }
43
44 /**
45  * Implements hook_menu_links_discovered_alter().
46  *
47  * Rewrites the menu entries for filter module that relate to the configuration
48  * of text editors.
49  */
50 function editor_menu_links_discovered_alter(array &$links) {
51   $links['filter.admin_overview']['title'] = new TranslatableMarkup('Text formats and editors');
52   $links['filter.admin_overview']['description'] = new TranslatableMarkup('Select and configure text editors, and how content is filtered when displayed.');
53 }
54
55 /**
56  * Implements hook_element_info_alter().
57  *
58  * Extends the functionality of text_format elements (provided by Filter
59  * module), so that selecting a text format notifies a client-side text editor
60  * when it should be enabled or disabled.
61  *
62  * @see \Drupal\filter\Element\TextFormat
63  */
64 function editor_element_info_alter(&$types) {
65   $types['text_format']['#pre_render'][] = 'element.editor:preRenderTextFormat';
66 }
67
68 /**
69  * Implements hook_form_FORM_ID_alter() for \Drupal\filter\FilterFormatListBuilder.
70  *
71  * Implements hook_field_formatter_info_alter().
72  *
73  * @see quickedit_field_formatter_info_alter()
74  */
75 function editor_field_formatter_info_alter(&$info) {
76   // Update \Drupal\text\Plugin\Field\FieldFormatter\TextDefaultFormatter's
77   // annotation to indicate that it supports the 'editor' in-place editor
78   // provided by this module.
79   $info['text_default']['quickedit'] = ['editor' => 'editor'];
80 }
81
82 /**
83  * Implements hook_form_FORM_ID_alter().
84  */
85 function editor_form_filter_admin_overview_alter(&$form, FormStateInterface $form_state) {
86   // @todo Cleanup column injection: https://www.drupal.org/node/1876718.
87   // Splice in the column for "Text editor" into the header.
88   $position = array_search('name', $form['formats']['#header']) + 1;
89   $start = array_splice($form['formats']['#header'], 0, $position, ['editor' => t('Text editor')]);
90   $form['formats']['#header'] = array_merge($start, $form['formats']['#header']);
91
92   // Then splice in the name of each text editor for each text format.
93   $editors = \Drupal::service('plugin.manager.editor')->getDefinitions();
94   foreach (Element::children($form['formats']) as $format_id) {
95     $editor = editor_load($format_id);
96     $editor_name = ($editor && isset($editors[$editor->getEditor()])) ? $editors[$editor->getEditor()]['label'] : '—';
97     $editor_column['editor'] = ['#markup' => $editor_name];
98     $position = array_search('name', array_keys($form['formats'][$format_id])) + 1;
99     $start = array_splice($form['formats'][$format_id], 0, $position, $editor_column);
100     $form['formats'][$format_id] = array_merge($start, $form['formats'][$format_id]);
101   }
102 }
103
104 /**
105  * Implements hook_form_BASE_FORM_ID_alter() for \Drupal\filter\FilterFormatEditForm.
106  */
107 function editor_form_filter_format_form_alter(&$form, FormStateInterface $form_state) {
108   $editor = $form_state->get('editor');
109   if ($editor === NULL) {
110     $format = $form_state->getFormObject()->getEntity();
111     $format_id = $format->isNew() ? NULL : $format->id();
112     $editor = editor_load($format_id);
113     $form_state->set('editor', $editor);
114   }
115
116   // Associate a text editor with this text format.
117   $manager = \Drupal::service('plugin.manager.editor');
118   $editor_options = $manager->listOptions();
119   $form['editor'] = [
120     // Position the editor selection before the filter settings (weight of 0),
121     // but after the filter label and name (weight of -20).
122     '#weight' => -9,
123   ];
124   $form['editor']['editor'] = [
125     '#type' => 'select',
126     '#title' => t('Text editor'),
127     '#options' => $editor_options,
128     '#empty_option' => t('None'),
129     '#default_value' => $editor ? $editor->getEditor() : '',
130     '#ajax' => [
131       'trigger_as' => ['name' => 'editor_configure'],
132       'callback' => 'editor_form_filter_admin_form_ajax',
133       'wrapper' => 'editor-settings-wrapper',
134     ],
135     '#weight' => -10,
136   ];
137   $form['editor']['configure'] = [
138     '#type' => 'submit',
139     '#name' => 'editor_configure',
140     '#value' => t('Configure'),
141     '#limit_validation_errors' => [['editor']],
142     '#submit' => ['editor_form_filter_admin_format_editor_configure'],
143     '#ajax' => [
144       'callback' => 'editor_form_filter_admin_form_ajax',
145       'wrapper' => 'editor-settings-wrapper',
146     ],
147     '#weight' => -10,
148     '#attributes' => ['class' => ['js-hide']],
149   ];
150
151   // If there aren't any options (other than "None"), disable the select list.
152   if (empty($editor_options)) {
153     $form['editor']['editor']['#disabled'] = TRUE;
154     $form['editor']['editor']['#description'] = t('This option is disabled because no modules that provide a text editor are currently enabled.');
155   }
156
157   $form['editor']['settings'] = [
158     '#tree' => TRUE,
159     '#weight' => -8,
160     '#type' => 'container',
161     '#id' => 'editor-settings-wrapper',
162     '#attached' => [
163       'library' => [
164         'editor/drupal.editor.admin',
165       ],
166     ],
167   ];
168
169   // Add editor-specific validation and submit handlers.
170   if ($editor) {
171     /** @var $plugin \Drupal\editor\Plugin\EditorPluginInterface */
172     $plugin = $manager->createInstance($editor->getEditor());
173     $settings_form = [];
174     $settings_form['#element_validate'][] = [$plugin, 'validateConfigurationForm'];
175     $form['editor']['settings']['subform'] = $plugin->buildConfigurationForm($settings_form, $form_state);
176     $form['editor']['settings']['subform']['#parents'] = ['editor', 'settings'];
177     $form['actions']['submit']['#submit'][] = [$plugin, 'submitConfigurationForm'];
178   }
179
180   $form['#validate'][] = 'editor_form_filter_admin_format_validate';
181   $form['actions']['submit']['#submit'][] = 'editor_form_filter_admin_format_submit';
182 }
183
184 /**
185  * Button submit handler for filter_format_form()'s 'editor_configure' button.
186  */
187 function editor_form_filter_admin_format_editor_configure($form, FormStateInterface $form_state) {
188   $editor = $form_state->get('editor');
189   $editor_value = $form_state->getValue(['editor', 'editor']);
190   if ($editor_value !== NULL) {
191     if ($editor_value === '') {
192       $form_state->set('editor', FALSE);
193     }
194     elseif (empty($editor) || $editor_value !== $editor->getEditor()) {
195       $format = $form_state->getFormObject()->getEntity();
196       $editor = Editor::create([
197         'format' => $format->isNew() ? NULL : $format->id(),
198         'editor' => $editor_value,
199       ]);
200       $form_state->set('editor', $editor);
201     }
202   }
203   $form_state->setRebuild();
204 }
205
206 /**
207  * AJAX callback handler for filter_format_form().
208  */
209 function editor_form_filter_admin_form_ajax($form, FormStateInterface $form_state) {
210   return $form['editor']['settings'];
211 }
212
213 /**
214  * Additional validate handler for filter_format_form().
215  */
216 function editor_form_filter_admin_format_validate($form, FormStateInterface $form_state) {
217   // This validate handler is not applicable when using the 'Configure' button.
218   if ($form_state->getTriggeringElement()['#name'] === 'editor_configure') {
219     return;
220   }
221
222   // When using this form with JavaScript disabled in the browser, the
223   // 'Configure' button won't be clicked automatically. So, when the user has
224   // selected a text editor and has then clicked 'Save configuration', we should
225   // point out that the user must still configure the text editor.
226   if ($form_state->getValue(['editor', 'editor']) !== '' && !$form_state->get('editor')) {
227     $form_state->setErrorByName('editor][editor', t('You must configure the selected text editor.'));
228   }
229 }
230
231 /**
232  * Additional submit handler for filter_format_form().
233  */
234 function editor_form_filter_admin_format_submit($form, FormStateInterface $form_state) {
235   // Delete the existing editor if disabling or switching between editors.
236   $format = $form_state->getFormObject()->getEntity();
237   $format_id = $format->isNew() ? NULL : $format->id();
238   $original_editor = editor_load($format_id);
239   if ($original_editor && $original_editor->getEditor() != $form_state->getValue(['editor', 'editor'])) {
240     $original_editor->delete();
241   }
242
243   // Create a new editor or update the existing editor.
244   if ($editor = $form_state->get('editor')) {
245     // Ensure the text format is set: when creating a new text format, this
246     // would equal the empty string.
247     $editor->set('format', $format_id);
248     $editor->setSettings($form_state->getValue(['editor', 'settings']));
249     $editor->save();
250   }
251 }
252
253 /**
254  * Loads an individual configured text editor based on text format ID.
255  *
256  * @param int $format_id
257  *   A text format ID.
258  *
259  * @return \Drupal\editor\Entity\Editor|null
260  *   A text editor object, or NULL.
261  */
262 function editor_load($format_id) {
263   // Load all the editors at once here, assuming that either no editors or more
264   // than one editor will be needed on a page (such as having multiple text
265   // formats for administrators). Loading a small number of editors all at once
266   // is more efficient than loading multiple editors individually.
267   $editors = Editor::loadMultiple();
268   return isset($editors[$format_id]) ? $editors[$format_id] : NULL;
269 }
270
271 /**
272  * Applies text editor XSS filtering.
273  *
274  * @param string $html
275  *   The HTML string that will be passed to the text editor.
276  * @param \Drupal\filter\FilterFormatInterface|null $format
277  *   The text format whose text editor will be used or NULL if the previously
278  *   defined text format is now disabled.
279  * @param \Drupal\filter\FilterFormatInterface $original_format|null
280  *   (optional) The original text format (i.e. when switching text formats,
281  *   $format is the text format that is going to be used, $original_format is
282  *   the one that was being used initially, the one that is stored in the
283  *   database when editing).
284  *
285  * @return string|false
286  *   The XSS filtered string or FALSE when no XSS filtering needs to be applied,
287  *   because one of the next conditions might occur:
288  *   - No text editor is associated with the text format,
289  *   - The previously defined text format is now disabled,
290  *   - The text editor is safe from XSS,
291  *   - The text format does not use any XSS protection filters.
292  *
293  * @see https://www.drupal.org/node/2099741
294  */
295 function editor_filter_xss($html, FilterFormatInterface $format = NULL, FilterFormatInterface $original_format = NULL) {
296   $editor = $format ? editor_load($format->id()) : NULL;
297
298   // If no text editor is associated with this text format or the previously
299   // defined text format is now disabled, then we don't need text editor XSS
300   // filtering either.
301   if (!isset($editor)) {
302     return FALSE;
303   }
304
305   // If the text editor associated with this text format guarantees security,
306   // then we also don't need text editor XSS filtering.
307   $definition = \Drupal::service('plugin.manager.editor')->getDefinition($editor->getEditor());
308   if ($definition['is_xss_safe'] === TRUE) {
309     return FALSE;
310   }
311
312   // If there is no filter preventing XSS attacks in the text format being used,
313   // then no text editor XSS filtering is needed either. (Because then the
314   // editing user can already be attacked by merely viewing the content.)
315   // e.g.: an admin user creates content in Full HTML and then edits it, no text
316   // format switching happens; in this case, no text editor XSS filtering is
317   // desirable, because it would strip style attributes, amongst others.
318   $current_filter_types = $format->getFilterTypes();
319   if (!in_array(FilterInterface::TYPE_HTML_RESTRICTOR, $current_filter_types, TRUE)) {
320     if ($original_format === NULL) {
321       return FALSE;
322     }
323     // Unless we are switching from another text format, in which case we must
324     // first check whether a filter preventing XSS attacks is used in that text
325     // format, and if so, we must still apply XSS filtering.
326     // e.g.: an anonymous user creates content in Restricted HTML, an admin user
327     // edits it (then no XSS filtering is applied because no text editor is
328     // used), and switches to Full HTML (for which a text editor is used). Then
329     // we must apply XSS filtering to protect the admin user.
330     else {
331       $original_filter_types = $original_format->getFilterTypes();
332       if (!in_array(FilterInterface::TYPE_HTML_RESTRICTOR, $original_filter_types, TRUE)) {
333         return FALSE;
334       }
335     }
336   }
337
338   // Otherwise, apply the text editor XSS filter. We use the default one unless
339   // a module tells us to use a different one.
340   $editor_xss_filter_class = '\Drupal\editor\EditorXssFilter\Standard';
341   \Drupal::moduleHandler()->alter('editor_xss_filter', $editor_xss_filter_class, $format, $original_format);
342
343   return call_user_func($editor_xss_filter_class . '::filterXss', $html, $format, $original_format);
344 }
345
346 /**
347  * Implements hook_entity_insert().
348  */
349 function editor_entity_insert(EntityInterface $entity) {
350   // Only act on content entities.
351   if (!($entity instanceof FieldableEntityInterface)) {
352     return;
353   }
354   $referenced_files_by_field = _editor_get_file_uuids_by_field($entity);
355   foreach ($referenced_files_by_field as $field => $uuids) {
356     _editor_record_file_usage($uuids, $entity);
357   }
358 }
359
360 /**
361  * Implements hook_entity_update().
362  */
363 function editor_entity_update(EntityInterface $entity) {
364   // Only act on content entities.
365   if (!($entity instanceof FieldableEntityInterface)) {
366     return;
367   }
368
369   // On new revisions, all files are considered to be a new usage and no
370   // deletion of previous file usages are necessary.
371   if (!empty($entity->original) && $entity->getRevisionId() != $entity->original->getRevisionId()) {
372     $referenced_files_by_field = _editor_get_file_uuids_by_field($entity);
373     foreach ($referenced_files_by_field as $field => $uuids) {
374       _editor_record_file_usage($uuids, $entity);
375     }
376   }
377   // On modified revisions, detect which file references have been added (and
378   // record their usage) and which ones have been removed (delete their usage).
379   // File references that existed both in the previous version of the revision
380   // and in the new one don't need their usage to be updated.
381   else {
382     $original_uuids_by_field = _editor_get_file_uuids_by_field($entity->original);
383     $uuids_by_field = _editor_get_file_uuids_by_field($entity);
384
385     // Detect file usages that should be incremented.
386     foreach ($uuids_by_field as $field => $uuids) {
387       $added_files = array_diff($uuids_by_field[$field], $original_uuids_by_field[$field]);
388       _editor_record_file_usage($added_files, $entity);
389     }
390
391     // Detect file usages that should be decremented.
392     foreach ($original_uuids_by_field as $field => $uuids) {
393       $removed_files = array_diff($original_uuids_by_field[$field], $uuids_by_field[$field]);
394       _editor_delete_file_usage($removed_files, $entity, 1);
395     }
396   }
397 }
398
399 /**
400  * Implements hook_entity_delete().
401  */
402 function editor_entity_delete(EntityInterface $entity) {
403   // Only act on content entities.
404   if (!($entity instanceof FieldableEntityInterface)) {
405     return;
406   }
407   $referenced_files_by_field = _editor_get_file_uuids_by_field($entity);
408   foreach ($referenced_files_by_field as $field => $uuids) {
409     _editor_delete_file_usage($uuids, $entity, 0);
410   }
411 }
412
413 /**
414  * Implements hook_entity_revision_delete().
415  */
416 function editor_entity_revision_delete(EntityInterface $entity) {
417   // Only act on content entities.
418   if (!($entity instanceof FieldableEntityInterface)) {
419     return;
420   }
421   $referenced_files_by_field = _editor_get_file_uuids_by_field($entity);
422   foreach ($referenced_files_by_field as $field => $uuids) {
423     _editor_delete_file_usage($uuids, $entity, 1);
424   }
425 }
426
427 /**
428  * Records file usage of files referenced by formatted text fields.
429  *
430  * Every referenced file that does not yet have the FILE_STATUS_PERMANENT state,
431  * will be given that state.
432  *
433  * @param array $uuids
434  *   An array of file entity UUIDs.
435  * @param EntityInterface $entity
436  *   An entity whose fields to inspect for file references.
437  */
438 function _editor_record_file_usage(array $uuids, EntityInterface $entity) {
439   foreach ($uuids as $uuid) {
440     if ($file = \Drupal::entityManager()->loadEntityByUuid('file', $uuid)) {
441       if ($file->status !== FILE_STATUS_PERMANENT) {
442         $file->status = FILE_STATUS_PERMANENT;
443         $file->save();
444       }
445       \Drupal::service('file.usage')->add($file, 'editor', $entity->getEntityTypeId(), $entity->id());
446     }
447   }
448 }
449
450 /**
451  * Deletes file usage of files referenced by formatted text fields.
452  *
453  * @param array $uuids
454  *   An array of file entity UUIDs.
455  * @param EntityInterface $entity
456  *   An entity whose fields to inspect for file references.
457  * @param $count
458  *   The number of references to delete. Should be 1 when deleting a single
459  *   revision and 0 when deleting an entity entirely.
460  *
461  * @see \Drupal\file\FileUsage\FileUsageInterface::delete()
462  */
463 function _editor_delete_file_usage(array $uuids, EntityInterface $entity, $count) {
464   foreach ($uuids as $uuid) {
465     if ($file = \Drupal::entityManager()->loadEntityByUuid('file', $uuid)) {
466       \Drupal::service('file.usage')->delete($file, 'editor', $entity->getEntityTypeId(), $entity->id(), $count);
467     }
468   }
469 }
470
471 /**
472  * Implements hook_file_download().
473  *
474  * @see file_file_download()
475  * @see file_get_file_references()
476  */
477 function editor_file_download($uri) {
478   // Get the file record based on the URI. If not in the database just return.
479   /** @var \Drupal\file\FileInterface[] $files */
480   $files = \Drupal::entityTypeManager()
481     ->getStorage('file')
482     ->loadByProperties(['uri' => $uri]);
483   if (count($files)) {
484     foreach ($files as $item) {
485       // Since some database servers sometimes use a case-insensitive comparison
486       // by default, double check that the filename is an exact match.
487       if ($item->getFileUri() === $uri) {
488         $file = $item;
489         break;
490       }
491     }
492   }
493   if (!isset($file)) {
494     return;
495   }
496
497   // Temporary files are handled by file_file_download(), so nothing to do here
498   // about them.
499   // @see file_file_download()
500
501   // Find out if any editor-backed field contains the file.
502   $usage_list = \Drupal::service('file.usage')->listUsage($file);
503
504   // Stop processing if there are no references in order to avoid returning
505   // headers for files controlled by other modules. Make an exception for
506   // temporary files where the host entity has not yet been saved (for example,
507   // an image preview on a node creation form) in which case, allow download by
508   // the file's owner.
509   if (empty($usage_list['editor']) && ($file->isPermanent() || $file->getOwnerId() != \Drupal::currentUser()->id())) {
510     return;
511   }
512
513   // Editor.module MUST NOT call $file->access() here (like file_file_download()
514   // does) as checking the 'download' access to a file entity would end up in
515   // FileAccessControlHandler->checkAccess() and ->getFileReferences(), which
516   // calls file_get_file_references(). This latter one would allow downloading
517   // files only handled by the file.module, which is exactly not the case right
518   // here. So instead we must check if the current user is allowed to view any
519   // of the entities that reference the image using the 'editor' module.
520   if ($file->isPermanent()) {
521     $referencing_entity_is_accessible = FALSE;
522     $references = empty($usage_list['editor']) ? [] : $usage_list['editor'];
523     foreach ($references as $entity_type => $entity_ids_usage_count) {
524       $referencing_entities = entity_load_multiple($entity_type, array_keys($entity_ids_usage_count));
525       /** @var \Drupal\Core\Entity\EntityInterface $referencing_entity */
526       foreach ($referencing_entities as $referencing_entity) {
527         if ($referencing_entity->access('view', NULL, TRUE)->isAllowed()) {
528           $referencing_entity_is_accessible = TRUE;
529           break 2;
530         }
531       }
532     }
533     if (!$referencing_entity_is_accessible) {
534       return -1;
535     }
536   }
537
538   // Access is granted.
539   $headers = file_get_content_headers($file);
540   return $headers;
541 }
542
543 /**
544  * Finds all files referenced (data-entity-uuid) by formatted text fields.
545  *
546  * @param EntityInterface $entity
547  *   An entity whose fields to analyze.
548  *
549  * @return array
550  *   An array of file entity UUIDs.
551  */
552 function _editor_get_file_uuids_by_field(EntityInterface $entity) {
553   $uuids = [];
554
555   $formatted_text_fields = _editor_get_formatted_text_fields($entity);
556   foreach ($formatted_text_fields as $formatted_text_field) {
557     $text = '';
558     $field_items = $entity->get($formatted_text_field);
559     foreach ($field_items as $field_item) {
560       $text .= $field_item->value;
561       if ($field_item->getFieldDefinition()->getType() == 'text_with_summary') {
562         $text .= $field_item->summary;
563       }
564     }
565     $uuids[$formatted_text_field] = _editor_parse_file_uuids($text);
566   }
567   return $uuids;
568 }
569
570 /**
571  * Determines the formatted text fields on an entity.
572  *
573  * @param \Drupal\Core\Entity\FieldableEntityInterface $entity
574  *   An entity whose fields to analyze.
575  *
576  * @return array
577  *   The names of the fields on this entity that support formatted text.
578  */
579 function _editor_get_formatted_text_fields(FieldableEntityInterface $entity) {
580   $field_definitions = $entity->getFieldDefinitions();
581   if (empty($field_definitions)) {
582     return [];
583   }
584
585   // Only return formatted text fields.
586   return array_keys(array_filter($field_definitions, function (FieldDefinitionInterface $definition) {
587     return in_array($definition->getType(), ['text', 'text_long', 'text_with_summary'], TRUE);
588   }));
589 }
590
591 /**
592  * Parse an HTML snippet for any linked file with data-entity-uuid attributes.
593  *
594  * @param string $text
595  *   The partial (X)HTML snippet to load. Invalid markup will be corrected on
596  *   import.
597  *
598  * @return array
599  *   An array of all found UUIDs.
600  */
601 function _editor_parse_file_uuids($text) {
602   $dom = Html::load($text);
603   $xpath = new \DOMXPath($dom);
604   $uuids = [];
605   foreach ($xpath->query('//*[@data-entity-type="file" and @data-entity-uuid]') as $node) {
606     $uuids[] = $node->getAttribute('data-entity-uuid');
607   }
608   return $uuids;
609 }
610
611 /**
612  * Implements hook_ENTITY_TYPE_presave().
613  *
614  * Synchronizes the editor status to its paired text format status.
615  */
616 function editor_filter_format_presave(FilterFormatInterface $format) {
617   // The text format being created cannot have a text editor yet.
618   if ($format->isNew()) {
619     return;
620   }
621
622   /** @var \Drupal\filter\FilterFormatInterface $original */
623   $original = \Drupal::entityManager()
624     ->getStorage('filter_format')
625     ->loadUnchanged($format->getOriginalId());
626
627   // If the text format status is the same, return early.
628   if (($status = $format->status()) === $original->status()) {
629     return;
630   }
631
632   /** @var \Drupal\editor\EditorInterface $editor */
633   if ($editor = Editor::load($format->id())) {
634     $editor->setStatus($status)->save();
635   }
636 }