Upgraded imagemagick and manually altered pdf to image module to handle changes....
[yaffs-website] / web / modules / contrib / paragraphs / paragraphs.module
1 <?php
2
3 /**
4  * @file
5  * Contains paragraphs.module
6  */
7
8 use Drupal\Core\Field\FieldConfigInterface;
9 use Drupal\Core\Url;
10 use Drupal\Core\Routing\RouteMatchInterface;
11 use Drupal\field\FieldStorageConfigInterface;
12 use Drupal\paragraphs\Entity\ParagraphsType;
13 use Drupal\Core\Render\Element;
14
15 /**
16  * Implements hook_help().
17  */
18 function paragraphs_help($route_name, RouteMatchInterface $route_match) {
19   switch ($route_name) {
20     // Main module help for the paragraphs module.
21     case 'help.page.paragraphs':
22       $output = '';
23       $output .= '<h3>' . t('About') . '</h3>';
24       $output .= '<p>' . t('The Paragraphs module provides a field type that can contain several other fields and thereby allows users to break content up on a page. Administrators can predefine <em>Paragraphs types</em> (for example a simple text block, a video, or a complex and configurable slideshow). Users can then place them on a page in any order instead of using a text editor to add and configure such elements. For more information, see the <a href=":online">online documentation for the Paragraphs module</a>.', [':online' => 'https://www.drupal.org/node/2444881']) . '</p>';
25       $output .= '<h3>' . t('Uses') . '</h3>';
26       $output .= '<dt>' . t('Creating Paragraphs types') . '</dt>';
27       $output .= '<dd>' . t('<em>Paragraphs types</em> can be created by clicking <em>Add Paragraphs type</em> on the <a href=":paragraphs">Paragraphs types page</a>. By default a new Paragraphs type does not contain any fields.', [':paragraphs' => Url::fromRoute('entity.paragraphs_type.collection')->toString()]) . '</dd>';
28       $output .= '<dt>' . t('Configuring Paragraphs types') . '</dt>';
29       $output .= '<dd>' . t('Administrators can add fields to a <em>Paragraphs type</em> on the <a href=":paragraphs">Paragraphs types page</a> if the <a href=":field_ui">Field UI</a> module is enabled. The form display and the display of the Paragraphs type can also be managed on this page. For more information on fields and entities, see the <a href=":field">Field module help page</a>.', [':paragraphs' => Url::fromRoute('entity.paragraphs_type.collection')->toString(), ':field' => Url::fromRoute('help.page', ['name' => 'field'])->toString(), ':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? Url::fromRoute('help.page', ['name' => 'field_ui'])->toString() : '#']) . '</dd>';
30       $output .= '<dt>' . t('Creating content with Paragraphs') . '</dt>';
31       $output .= '<dd>' . t('Administrators can add a <em>Paragraph</em> field to content types or other entities, and configure which <em>Paragraphs types</em> to include. When users create content, they can then add one or more paragraphs by choosing the appropriate type from the dropdown list. Users can also dragdrop these paragraphs. This allows users to add structure to a page or other content (for example by adding an image, a user reference, or a differently formatted block of text) more easily then including it all in one text field or by using fields in a pre-defined order.') . '</dd>';
32       return $output;
33     break;
34   }
35 }
36
37 function paragraphs_type_get_types() {
38   return ParagraphsType::loadMultiple();
39 }
40
41 function paragraphs_type_get_names() {
42   return array_map(function ($bundle_info) {
43     return $bundle_info['label'];
44   }, \Drupal::service('entity_type.bundle.info')->getBundleInfo('paragraphs_type'));
45 }
46
47 function paragraphs_type_load($name) {
48   return ParagraphsType::load($name);
49 }
50
51 /**
52  * Implements hook_theme().
53  */
54 function paragraphs_theme() {
55   return array(
56     'paragraph' => array(
57       'render element' => 'elements',
58     ),
59     'paragraphs_dropbutton_wrapper' => array(
60       'variables' => array('children' => NULL),
61     ),
62     'paragraphs_info_icon' => [
63       'variables' => [
64         'message' => NULL,
65         'icon' => NULL,
66       ],
67     ],
68     'paragraphs_add_dialog' => [
69       'render element' => 'element',
70       'template' => 'paragraphs-add-dialog',
71     ],
72     'paragraphs_actions' => [
73       'render element' => 'element',
74       'template' => 'paragraphs-actions',
75     ],
76   );
77 }
78
79 /**
80  * Implements hook_theme_suggestions_HOOK().
81  */
82 function paragraphs_theme_suggestions_paragraph(array $variables) {
83   $suggestions = array();
84   $paragraph = $variables['elements']['#paragraph'];
85   $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');
86
87   $suggestions[] = 'paragraph__' . $sanitized_view_mode;
88   $suggestions[] = 'paragraph__' . $paragraph->bundle();
89   $suggestions[] = 'paragraph__' . $paragraph->bundle() . '__' . $sanitized_view_mode;
90
91   return $suggestions;
92 }
93
94 /**
95  * Implements hook_form_FORM_ID_alter().
96  */
97 function paragraphs_form_entity_form_display_edit_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
98   $field_definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions($form['#entity_type'], $form['#bundle']);
99   // Loop over ERR field's display options with paragraph target type.
100   foreach (array_keys($field_definitions) as $field_name) {
101     if ($field_definitions[$field_name]->getType() == 'entity_reference_revisions') {
102       if ($field_definitions[$field_name]->getSettings()['target_type'] == 'paragraph') {
103         foreach (['options_buttons', 'options_select', 'entity_reference_revisions_autocomplete'] as $option) {
104           unset($form['fields'][$field_name]['plugin']['type']['#options'][$option]);
105         }
106       }
107     }
108   }
109 }
110
111 /**
112  * Implements hook_form_FORM_ID_alter().
113  */
114 function paragraphs_form_field_storage_config_edit_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
115   if ($form_state->getFormObject()->getEntity()->getType() == 'entity_reference') {
116     // Entity Reference fields are no longer supported to reference Paragraphs.
117     unset($form['settings']['target_type']['#options'][(string) t('Content')]['paragraph']);
118   }
119 }
120
121 /**
122  * Implements hook_form_FORM_ID_alter().
123  *
124  * Indicate unsupported multilingual paragraphs field configuration.
125  */
126 function paragraphs_form_field_config_edit_form_alter(&$form,  \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
127   $field = $form_state->getFormObject()->getEntity();
128
129   if (!\Drupal::hasService('content_translation.manager')) {
130     return;
131   }
132
133   $bundle_is_translatable = \Drupal::service('content_translation.manager')
134     ->isEnabled($field->getTargetEntityTypeId(), $field->getTargetBundle());
135
136   if (!$bundle_is_translatable
137     || $field->getType() != 'entity_reference_revisions'
138     || $field->getSetting('target_type') != 'paragraph') {
139     return;
140   }
141
142   // This is a translatable ERR field pointing to a paragraph.
143   $message_display = 'warning';
144   $message_text = t('Paragraphs fields do not support translation. See the <a href=":documentation">online documentation</a>.', [
145     ':documentation' => Url::fromUri('https://www.drupal.org/node/2735121')
146       ->toString()
147   ]);
148
149   if ($form['translatable']['#default_value'] == TRUE) {
150     $message_display = 'error';
151   }
152
153   $form['paragraphs_message'] = array(
154     '#type' => 'container',
155     '#markup' => $message_text,
156     '#attributes' => array(
157       'class' => array('messages messages--' . $message_display),
158     ),
159     '#weight' => 0,
160   );
161 }
162
163 /**
164  * Implements hook_module_implements_alter().
165  *
166  * Our paragraphs_form_field_config_edit_form_alter() needs to be run after
167  * that of the content_translation module in order to see the current state
168  * of the translation field.
169  *
170  * The hook here can't be more specific, as the $hook that's passed in to this
171  * function is form_alter, and not form_FORM_ID_alter.
172  */
173 function paragraphs_module_implements_alter(&$implementations, $hook) {
174   if ($hook == 'form_alter' && isset($implementations['paragraphs'])) {
175     $group = $implementations['paragraphs'];
176     unset($implementations['paragraphs']);
177     $implementations['paragraphs'] = $group;
178   }
179 }
180
181 /**
182  * Implements hook_form_FORM_ID_alter().
183  *
184  * Indicate unsupported multilingual paragraphs field configuration.
185  *
186  * Add a warning that paragraph fields can not be translated.
187  * Switch to error if a paragraph field is marked as translatable.
188  */
189 function paragraphs_form_language_content_settings_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
190   // Without it Paragraphs message are meaningless.
191   if (!\Drupal::hasService('content_translation.manager')) {
192     return;
193   }
194
195   $content_translation_manager = \Drupal::service('content_translation.manager');
196   $message_display = 'warning';
197   $message_text = t('(* unsupported) Paragraphs fields do not support translation. See the <a href=":documentation">online documentation</a>.', [
198     ':documentation' => Url::fromUri('https://www.drupal.org/node/2735121')
199       ->toString()]);
200   $map = \Drupal::service('entity_field.manager')->getFieldMapByFieldType('entity_reference_revisions');
201   foreach ($map as $entity_type_id => $info) {
202     if (!$content_translation_manager->isEnabled($entity_type_id)) {
203       continue;
204     }
205     $field_storage_definitions = \Drupal::service('entity_field.manager')->getFieldStorageDefinitions($entity_type_id);
206
207     /** @var \Drupal\Core\Field\FieldStorageDefinitionInterface  $storage_definition */
208     foreach ($field_storage_definitions as $name => $storage_definition) {
209       if ($storage_definition->getSetting('target_type') && $storage_definition->getSetting('target_type') == 'paragraph') {
210
211         // For configurable fields, check all bundles on which the field exists,
212         // for base fields that are translable, check all bundles,
213         // untranslatable base fields do not show up at all.
214         $bundles = [];
215         if ($storage_definition instanceof FieldStorageConfigInterface) {
216           $bundles = $storage_definition->getBundles();
217         }
218         elseif ($storage_definition->isTranslatable()) {
219           $bundles = Element::children($form['settings'][$entity_type_id]);
220         }
221         foreach($bundles as $bundle) {
222           if (!$content_translation_manager->isEnabled($entity_type_id, $bundle)) {
223             continue;
224           }
225
226           // Update the label and if the paragraph field is translatable,
227           // display an error message instead of just a warning.
228           if (isset($form['settings'][$entity_type_id][$bundle]['fields'][$name]['#label'])) {
229             $form['settings'][$entity_type_id][$bundle]['fields'][$name]['#label'] = t('@field_label (* unsupported)', ['@field_label' => $form['settings'][$entity_type_id][$bundle]['fields'][$name]['#label']]);
230           }
231           if (!empty($form['settings'][$entity_type_id][$bundle]['fields'][$name]['#default_value'])) {
232             $message_display = 'error';
233           }
234         }
235       }
236     }
237   }
238   $form['settings']['paragraphs_message'] = array(
239     '#type' => 'container',
240     '#markup' => $message_text,
241     '#attributes' => array(
242       'class' => array('messages messages--' . $message_display),
243     ),
244     '#weight' => 0,
245   );
246 }
247
248 /**
249  * Prepares variables for paragraph templates.
250  *
251  * Default template: paragraph.html.twig.
252  *
253  * Most themes use their own copy of paragraph.html.twig. The default is located
254  * inside "templates/paragraph.html.twig". Look in there for the
255  * full list of variables.
256  *
257  * @param array $variables
258  *   An associative array containing:
259  *   - elements: An array of elements to display in view mode.
260  *   - paragraph: The paragraph object.
261  *   - view_mode: View mode; e.g., 'full', 'teaser'...
262  */
263 function template_preprocess_paragraph(&$variables) {
264   $variables['view_mode'] = $variables['elements']['#view_mode'];
265   $variables['paragraph'] = $variables['elements']['#paragraph'];
266
267   // Helpful $content variable for templates.
268   $variables += array('content' => array());
269   foreach (Element::children($variables['elements']) as $key) {
270     $variables['content'][$key] = $variables['elements'][$key];
271   }
272
273   $paragraph_type = $variables['elements']['#paragraph']->getParagraphType();
274   foreach ($paragraph_type->getEnabledBehaviorPlugins() as $plugin_id => $plugin_value) {
275     $plugin_value->preprocess($variables);
276   }
277
278 }
279
280 /**
281  * Prepares variables for modal form add widget template.
282  *
283  * Default template: paragraphs-add-dialog.html.twig
284  *
285  * @param array $variables
286  *   An associative array containing:
287  *   - buttons: An array of buttons to display in the modal form.
288  */
289 function template_preprocess_paragraphs_add_dialog(&$variables) {
290   // Define variables for the template.
291   $variables += ['buttons' => []];
292   foreach (Element::children($variables['element']) as $key) {
293     if ($key == 'add_modal_form_area') {
294       // $add variable for the add button.
295       $variables['add'] = $variables['element'][$key];
296     }
297     else {
298       // Buttons for the paragraph types in the modal form.
299       $variables['buttons'][$key] = $variables['element'][$key];
300     }
301   }
302 }
303
304 /**
305  * Prepares variables for paragraphs_actions component.
306  *
307  * Default template: paragraphs-actions.html.twig.
308  *
309  * @param array $variables
310  *   An associative array containing:
311  *   - actions: An array of default action buttons.
312  *   - dropdown_actions: An array of buttons for dropdown.
313  */
314 function template_preprocess_paragraphs_actions(&$variables) {
315   // Define variables for the template.
316   $variables += ['actions' => [], 'dropdown_actions' => []];
317
318   $element = $variables['element'];
319
320   if (!empty($element['actions'])) {
321     $variables['actions'] = $element['actions'];
322   }
323
324   if (!empty($element['dropdown_actions'])) {
325     $variables['dropdown_actions'] = $element['dropdown_actions'];
326   }
327 }
328
329 /**
330  * Implements hook_preprocess_HOOK() for field_multiple_value_form().
331  */
332 function paragraphs_preprocess_field_multiple_value_form(&$variables) {
333   if (count($variables['element']['#field_parents']) === 0 && isset($variables['table']['#rows'])) {
334     // Find paragraph_actions and move to header.
335     // @see template_preprocess_field_multiple_value_form()
336     if (!empty($variables['table']['#rows'][0]['data'][1]['data']['#paragraphs_header'])) {
337       $variables['table']['#header'][0]['data'] = [
338         'title' => $variables['table']['#header'][0]['data'],
339         'button' => $variables['table']['#rows'][0]['data'][1]['data'],
340       ];
341       unset($variables['table']['#rows'][0]);
342     }
343   }
344 }
345
346 /**
347  * Implements hook_libraries_info().
348  */
349 function paragraphs_libraries_info() {
350   $libraries = [
351     'Sortable' => [
352       'name' => 'Sortable',
353       'vendor url' => 'https://github.com/RubaXa/Sortable',
354       'download url' => 'https://github.com/RubaXa/Sortable/releases',
355       'files' => [
356         'js' => [
357           'Sortable.min.js' => [],
358         ],
359       ],
360       'version arguments' => [
361         // The version is at the end of the file, which is currently about 15k
362         // characters long.
363         'file' => 'Sortable.min.js',
364         'pattern' => '/\.version="(.*?)"/',
365         'lines' => 2,
366         'cols' => 20000
367       ]
368     ],
369   ];
370   return $libraries;
371 }
372
373 /**
374  * Implements hook_library_info_alter().
375  */
376 function paragraphs_library_info_alter(&$libraries, $extension) {
377   if ($extension != 'paragraphs') {
378     return;
379   }
380
381   if (\Drupal::moduleHandler()->moduleExists('libraries')) {
382     $info = libraries_detect('Sortable');
383   }
384   else {
385     // If the library module is not installed, hardcode the path and fetch
386     // the required information ourself.
387     $library_path = 'libraries/Sortable';
388     $file = 'Sortable.min.js';
389     $path = DRUPAL_ROOT . '/' . $library_path . '/' . $file;
390     if (file_exists($path)) {
391       if (preg_match('/\.version="(.*?)"/', file_get_contents($path), $version)) {
392         $info = [
393           'installed' => TRUE,
394           'version' => $version[1],
395           'library path' => $library_path,
396           'files' => [
397             'js' => [
398               $file => [],
399             ],
400           ],
401         ];
402       }
403     }
404   }
405
406   if (!empty($info['installed'])) {
407     $libraries['sortable'] += [
408       'version' => $info['version'],
409     ];
410     // Self hosted player, use files from library definition.
411     if (!empty($info['files']['js'])) {
412       foreach ($info['files']['js'] as $filename => $options) {
413         $libraries['sortable']['js']["/{$info['library path']}/{$filename}"] = $options;
414       }
415     }
416   }
417   else {
418     // Unset the libraries if we failed to detect them.
419     unset($libraries['sortable']);
420     unset($libraries['paragraphs-dragdrop']);
421   }
422
423   return $libraries;
424 }