-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathghi_content.module
604 lines (547 loc) · 20.4 KB
/
ghi_content.module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
<?php
/**
* @file
* Hook implementations for GHI Content.
*/
use Drupal\Core\Batch\BatchBuilder;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Entity\Entity\EntityViewDisplay;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Link;
use Drupal\Core\Render\Markup;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Url;
use Drupal\file\Plugin\Field\FieldType\FileFieldItemList;
use Drupal\ghi_content\Controller\MigrationBatchController;
use Drupal\ghi_content\Entity\Article;
use Drupal\ghi_content\Entity\ContentBase;
use Drupal\ghi_content\Entity\Document;
use Drupal\ghi_content\RemoteContent\RemoteContentImageInterface;
use Drupal\ghi_sections\Entity\Section;
use Drupal\ghi_sections\SectionManager;
use Drupal\hpc_common\Helpers\RequestHelper;
use Drupal\layout_builder\SectionStorageInterface;
use Drupal\node\NodeInterface;
/**
* Implements hook_entity_bundle_info_alter().
*/
function ghi_content_entity_bundle_info_alter(array &$bundles) {
$bundles['node']['article']['class'] = Article::class;
$bundles['node']['article']['label'] = t('Article');
$bundles['node']['document']['class'] = Document::class;
$bundles['node']['document']['label'] = t('Document');
}
/**
* Implements hook_theme().
*/
function ghi_content_theme($existing, $type, $theme, $path) {
return [
'article_collection_cards' => [
'variables' => [
'articles' => [],
'options' => [
'alignment' => 'horizontal',
'columns' => 3,
'featured' => NULL,
],
],
'file' => 'ghi_content.theme.inc',
'template' => 'article-collection-cards',
],
'article_collection_table' => [
'variables' => [
'articles' => [],
],
'file' => 'ghi_content.theme.inc',
'template' => 'article-collection-table',
],
'related_articles_cards' => [
'variables' => [
'articles' => [],
],
'file' => 'ghi_content.theme.inc',
'template' => 'related-articles-cards',
],
'related_sections' => [
'variables' => [
'sections' => [],
'options' => [
'alignment' => 'horizontal',
'columns' => 3,
],
],
'file' => 'ghi_content.theme.inc',
'template' => 'related-sections',
],
];
}
/**
* Implements hook_batch_alter().
*/
function ghi_content_batch_alter(&$batch) {
$targeted_callback = '\Drupal\migrate_tools\MigrateBatchExecutable::batchProcessImport';
$targeted_migrations = [
'articles_hpc_content_module' => 'ghi_content.manager.article',
'documents_hpc_content_module' => 'ghi_content.manager.document',
];
$current_set = $batch['current_set'];
$operations = &$batch['sets'][$current_set]['operations'];
$callback = $operations[0][0] ?? NULL;
$migration_name = $operations[0][1][0] ?? NULL;
if ($callback != $targeted_callback || !array_key_exists($migration_name, $targeted_migrations)) {
return;
}
// Add a post-process batch set to article imports to make sure that articles
// that are not available on the remote source anymore will get unpublished.
$placeholders = [
'@name' => $migration_name,
];
/** @var \Drupal\ghi_content\ContentManager\DocumentManager $document_manager */
$content_manager = \Drupal::service($targeted_migrations[$migration_name]);
$batch_builder = (new BatchBuilder())
->setTitle(t('Post process @name', $placeholders))
->setInitMessage(t('Start post-processing for @name', $placeholders))
->setProgressMessage(t('Post-processing @name', $placeholders))
->addOperation(
[MigrationBatchController::class, 'batchProcessCleanup'],
[$operations[0][1][0], $operations[0][1][1], $content_manager]
)
->setFinishCallback([MigrationBatchController::class, 'batchFinished']);
batch_set($batch_builder->toArray());
}
/**
* Implements hook_layout_builder_ipe_links_alter().
*
* This adds a destination parameter to selected layout builder ipe routes.
*/
function ghi_content_layout_builder_ipe_links_alter(array &$links, SectionStorageInterface $section_storage, EntityInterface $entity) {
if (!$entity instanceof ContentBase) {
// We only support this for content entites.
return;
}
$route_names = [
'layout_builder_ipe.entity.edit',
'layout_builder_ipe.entity.override',
];
foreach ($links as &$link) {
if (!$link instanceof Link || !$link->getUrl()->isRouted()) {
continue;
}
$url = $link->getUrl();
if (!in_array($url->getRouteName(), $route_names)) {
continue;
}
$request = \Drupal::request();
$route_params = $request->attributes->get('_route_params');
$node = $route_params['node'] ?? NULL;
if (!$node instanceof ContentBase) {
return;
}
$query = $url->getOption('query');
$query['destination'] = $request->query->has('destination') ? $request->query->get('destination') : $request->getPathInfo();
$url->setOption('query', $query);
}
}
/**
* Implements hook_contextual_links_alter().
*
* Disable contextual links to declutter the interface. If it wouldn't be for
* layout builder who needs the contextual links for it's own interface, we
* could just disable the module entirely.
* See https://www.drupal.org/project/drupal/issues/3042516
*/
function ghi_content_contextual_links_alter(array &$links, $group, array $route_parameters) {
$allowed_groups = ['layout_builder_block'];
if (!in_array($group, $allowed_groups)) {
return;
}
/** @var \Drupal\ghi_content\ContextualLinks\BlockHandler $contextual_links_block_handler */
$contextual_links_block_handler = \Drupal::service('ghi_content.contextual_links.block_handler');
$contextual_links_block_handler->alterLinks($links, $group, $route_parameters);
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function ghi_content_form_ghi_subpages_admin_views_form_alter(array &$form, FormStateInterface $form_state) {
$node = $form['#node'];
$overview_links = [
Link::createFromRoute(t('Article pages'), 'ghi_content.node.articles', ['node' => $node->id()])->toString(),
Link::createFromRoute(t('Document pages'), 'ghi_content.node.documents', ['node' => $node->id()])->toString(),
];
$form['description']['#markup'] .= ' ' . t('Additional content that is linked indirectly via tags can be found on these pages: @overview_links', [
'@overview_links' => Markup::create(implode(', ', $overview_links)),
]);
}
/**
* Implements hook_form_FORM_ID_alter().
*
* Used to disable fields that are automatically populated.
*/
function ghi_content_form_node_article_edit_form_alter(array &$form, FormStateInterface $form_state) {
/** @var \Drupal\ghi_content\ContentManager\ArticleManager $article_manager */
$article_manager = \Drupal::getContainer()->get('ghi_content.manager.article');
$article_manager->nodeEditFormAlter($form, $form_state);
return $form;
}
/**
* Implements hook_form_FORM_ID_alter().
*
* Used to disable fields that are automatically populated.
*/
function ghi_content_form_node_document_edit_form_alter(array &$form, FormStateInterface $form_state) {
/** @var \Drupal\ghi_content\ContentManager\DocumentManager $article_manager */
$document_manager = \Drupal::getContainer()->get('ghi_content.manager.document');
$document_manager->nodeEditFormAlter($form, $form_state);
return $form;
}
/**
* Implements hook_entity_build_defaults_alter().
*
* This is used to add cache keys for context nodes to entity builds of content
* like documents and articles. Rendered links to the content can differ not
* only by url, but also by manually assigning context in elements like the
* DocumentChapter block and we don't want those to be cached together.
*/
function ghi_content_entity_build_defaults_alter(array &$build, EntityInterface $entity, $view_mode) {
if (!$entity instanceof ContentBase || !$context_node = $entity->getContextNode()) {
return;
}
$build['#cache']['keys'][] = 'context_node:' . $context_node->bundle() . ':' . $context_node->id();
}
/**
* Implements hook_current_section_alter().
*/
function ghi_content_current_section_alter(&$section, $node) {
if ($node instanceof Section) {
$section = $node;
}
if (!$node instanceof ContentBase) {
return NULL;
}
$context_node = $node->getContextNode();
if ($context_node instanceof Section) {
$section = $context_node;
}
elseif ($context_node instanceof ContentBase && $context_node->getContextNode()) {
ghi_content_current_section_alter($section, $context_node->getContextNode());
}
}
/**
* Implements hook_ENTITY_TYPE_predelete() for node entities.
*/
function ghi_content_node_predelete(NodeInterface $node) {
/** @var \Drupal\ghi_content\ContentManager\ManagerFactory $manager_factory */
$manager_factory = \Drupal::getContainer()->get('ghi_content.manager.factory');
$content_manager = $manager_factory->getContentManager($node);
if ($content_manager) {
$content_manager->cleanupContentOnDelete($node);
}
}
/**
* Implements hook_preprocess_html().
*/
function ghi_content_preprocess_html(&$variables) {
$node = RequestHelper::getCurrentNodeObject();
if (!$node instanceof ContentBase || !$node->access()) {
return;
}
if ($node->isStandalonePage()) {
$variables['attributes']['class'][] = 'standalone-page';
}
}
/**
* Implements hook_preprocess_page().
*
* This is used to add the configured hero image (or a default image) to the
* page title region.
*
* This code assumes that there is a page_image region in the theme.
*/
function ghi_content_preprocess_page(&$variables) {
$region_name = 'page_image';
if (!array_key_exists($region_name, $variables['page'])) {
return;
}
$node = RequestHelper::getCurrentNodeObject();
if (!$node instanceof ContentBase || !$node->access()) {
return;
}
$image_node = $node->getNodeWithHeroImage();
if (!$image_node) {
return;
}
// We do not check if the field has actual values, because we might want to
// show a default image.
$image_field = $image_node->getImage();
if (!$image_field || $image_field->isEmpty()) {
// Don't show default images in the page view.
return;
}
$image_style_name = 'hero';
// Go through some trouble to show a responsive image here.
$repsonsive_image_style_id = $image_style_name;
$repsonsive_image_style_storage = \Drupal::service('entity_type.manager')->getStorage('responsive_image_style');
$image_style_storage = \Drupal::service('entity_type.manager')->getStorage('image_style');
// Collect cache tags to be added for each item in the field.
$responsive_image_style = $repsonsive_image_style_storage->load($repsonsive_image_style_id);
$image_styles_to_load = [];
$cache_tags = $image_node->getCacheTags();
if ($responsive_image_style) {
$cache_tags = Cache::mergeTags($cache_tags, $responsive_image_style->getCacheTags());
$image_styles_to_load = $responsive_image_style->getImageStyleIds();
}
$image_styles = $image_style_storage->loadMultiple($image_styles_to_load);
foreach ($image_styles as $image_style) {
$cache_tags = Cache::mergeTags($cache_tags, $image_style->getCacheTags());
}
/** @var \Drupal\ghi_content\ContentManager\ManagerFactory $manager_factory */
$manager_factory = \Drupal::getContainer()->get('ghi_content.manager.factory');
$content_manager = $manager_factory->getContentManager($image_node);
if ($content_manager) {
$content = $content_manager->loadRemoteContentForNode($image_node);
}
if (!$image_node instanceof ContentBase) {
$image_build = $image_field->view([
'label' => 'hidden',
'settings' => [
'responsive_image_style' => $image_style_name,
'image_link' => NULL,
'include_credits' => TRUE,
],
]);
}
else {
$image_build = [
'#theme' => 'ghi_image',
'#responsive_image_style' => $responsive_image_style,
'#url' => $image_field->entity->getFileUri(),
'#caption' => $content && $content instanceof RemoteContentImageInterface ? $content->getImageCaptionMarkup(TRUE) : NULL,
'#alt' => $image_field->alt,
'#title' => $image_field->title,
'#cache' => [
'tags' => $cache_tags,
'contexts' => ['url.path'],
],
];
}
if ($image_build) {
$image['#label_display'] = 'hidden';
$variables['page'][$region_name] = ['hero_image' => $image_build] + $variables['page'][$region_name];
}
}
/**
* Implements hook_preprocess_page_title().
*/
function ghi_content_preprocess_page_title(&$variables) {
$node = RequestHelper::getCurrentNodeObject();
$is_admin_route = \Drupal::service('router.admin_context')->isAdminRoute();
if ($is_admin_route || !$node instanceof Article || !empty($variables['#protected'])) {
return;
}
if ($node->getContextNode()) {
$variables['title'] = $node->getContextNode()->label();
}
}
/**
* Implements hook_preprocess_node().
*/
function ghi_content_preprocess_node(&$variables) {
/** @var \Drupal\ghi_content\Entity\ContentBase $node */
$node = $variables['node'];
if ($node instanceof ContentBase && (!$node->isStandalonePage() || $node instanceof Article)) {
$variables['metadata'] = [
'#theme' => 'item_list',
'#items' => $node->getPageMetaData(),
'#full_width' => TRUE,
];
}
if ($node instanceof ContentBase && !$node->shouldDisplayHeroImage()) {
// If the article is configured to hide the image, hide it everywhere.
/** @var \Drupal\Core\Entity\Entity\EntityViewDisplay $view_mode_entity */
$view_mode_entity = EntityViewDisplay::load('node.article.' . $variables['view_mode']);
/** @var \Drupal\file\Plugin\Field\FieldType\FileFieldItemList $items */
$items = $node->field_image;
if ($view_mode_entity && $items instanceof FileFieldItemList) {
$items->filter(function ($item) {
return FALSE;
});
$variables['content']['field_image'] = $view_mode_entity->getRenderer('field_image')?->view($items);
}
}
if ($node instanceof Document) {
$variables['document_summary'] = $node->getSummary();
}
}
/**
* Implements hook_preprocess_node().
*
* Filter out structural tags from the article grid view.
*/
function ghi_content_preprocess_field__field_tags(&$variables) {
$view_mode = $variables['element']['#view_mode'] ?? NULL;
$node = $variables['element']['#object'] ?? NULL;
if ($node instanceof Article && $view_mode == 'grid') {
$structural_tags = $node->getStructuralTags();
$remove_cache_tags = array_map(function ($term) {
return 'taxonomy_term:' . $term->id();
}, $structural_tags);
$variables['items'] = array_values(array_filter($variables['items'], function ($item) use ($remove_cache_tags) {
if (empty($item['content']['#cache']) || empty($item['content']['#cache']['tags'])) {
return TRUE;
}
return count(array_intersect($item['content']['#cache']['tags'], $remove_cache_tags)) == 0;
}));
}
}
/**
* Implements hook_preprocess_views_view_field().
*
* This is used to remove the section tags from the tags field in views that
* take tag ids as an argument in order to show articles belonging to a
* specific section.
*/
function ghi_content_preprocess_views_view_field__field_tags(&$variables) {
$valid_view_ids = ['content_by_tags'];
/** @var \Drupal\views\ViewExecutable $view */
$view = $variables['view'];
if (!in_array($view->storage->id(), $valid_view_ids)) {
return;
}
/** @var \Drupal\views\ResultRow $row */
$row = $variables['row'];
/** @var \Drupal\views\Plugin\views\field\EntityField $field */
$field = $variables['field'];
// Get the tags that are specific to each row and remove the term ids passed
// in as arguments.
$tags = array_diff($field->getValue($row), $view->args);
// Get the build items from the field and filter it be restricted to these
// tags.
$items = $field->getItems($row);
$items = array_filter($items, function ($item) use ($tags) {
return in_array($item['raw']->entity->id(), $tags);
});
// Then render again according to the options set in the view and overwrite
// the output.
$build = $field->renderItems(array_map(function ($item) {
return $item['rendered'];
}, $items));
$variables['output'] = $build;
}
/**
* Implements hook_local_actions_render_alter().
*
* This depends on https://www.drupal.org/project/drupal/issues/2585169.
*/
function ghi_content_local_actions_render_alter(&$data, $route_appears) {
$route_migration_map = [
'ghi_content.article_update' => 'articles_hpc_content_module',
'ghi_content.node.article_update' => 'articles_hpc_content_module',
'ghi_content.document_update' => 'documents_hpc_content_module',
'ghi_content.node.document_update' => 'documents_hpc_content_module',
];
foreach ($data as $link_key => &$element) {
if (!array_key_exists($link_key, $route_migration_map)) {
continue;
}
$migration_id = $route_migration_map[$link_key];
$migrate_last_imported_store = \Drupal::keyValue('migrate_last_imported');
$last_imported = $migrate_last_imported_store->get($migration_id);
$last_imported = $last_imported ? intval($last_imported / 1000) : NULL;
/** @var \Drupal\Core\Datetime\DateFormatterInterface $date_formatter */
$date_formatter = \Drupal::service('date.formatter');
if ($last_imported) {
$element['#link']['title'] = new TranslatableMarkup('@link_title<div class="article-update-info">Last updated: @last_updated ago</div>', [
'@link_title' => $element['#link']['title'],
'@last_updated' => $date_formatter->formatTimeDiffSince($last_imported),
]);
$element['#cache'] = ['max-age' => 0];
$element['#attached']['library'][] = 'ghi_content/admin.article_list';
}
}
}
/**
* Implements hook_entity_operation().
*/
function ghi_content_entity_operation(EntityInterface $entity) {
$account = \Drupal::currentUser();
if (!$entity instanceof NodeInterface || !in_array($entity->bundle(), SectionManager::SECTION_BUNDLES)) {
return;
}
$operations = [];
$bundles = [
'articles' => t('Article pages'),
'documents' => t('Document pages'),
];
foreach ($bundles as $bundle => $label) {
$route_name = 'ghi_content.node.' . $bundle;
$route_parameters = [
'node' => $entity->id(),
];
// If current user has access to route, then add the operation link.
/** @var \Drupal\Core\Access\AccessManagerInterface $access_manager */
$access_manager = \Drupal::service('access_manager');
if (!$access_manager->checkNamedRoute($route_name, $route_parameters, $account)) {
return;
}
$operations[$bundle] = [
'title' => $label,
'weight' => 50 + count($operations),
'url' => Url::fromRoute($route_name, $route_parameters),
];
}
return $operations;
}
// @codingStandardsIgnoreStart
// /**
// * Implements hook_node_access_records().
// *
// * The basic logic for the moment is that users with edit access to a section
// * should be able to view any articles listed in that section, whether
// * published or unpublished.
// */
// function ghi_content_node_access_records(NodeInterface $node) {
// $grants = [];
// if ($node instanceof Article || $node->isPublished()) {
// // Not an article node or already published.
// return $grants;
// }
// /** @var \Drupal\ghi_content\ContentManager\ArticleManager */
// $article_manager = \Drupal::service('ghi_content.manager.article');
// $sections = $article_manager->loadSectionsForNode($node);
// if (empty($sections)) {
// return $grants;
// }
// // Grant view access to all unpublished articles of a section.
// foreach ($sections as $section) {
// $grants[] = [
// 'realm' => 'ghi_content_article_access',
// 'gid' => $section->id(),
// 'grant_view' => 1,
// 'grant_update' => 0,
// 'grant_delete' => 0,
// 'priority' => 0,
// ];
// }
// return $grants;
// }
// /**
// * Implements hook_node_grants().
// */
// function ghi_content_node_grants(AccountInterface $account, $op) {
// $grants = [];
// $grants['ghi_content_article_access'] = [0];
// $user = User::load($account->id());
// if (!$user->hasField('field_team') || $user->get('field_team')->isEmpty()) {
// return $grants;
// }
// /** @var \Drupal\ghi_sections\SectionManager */
// $section_manager = \Drupal::service('ghi_sections.manager');
// // Load the available sections for the users team.
// $sections = $section_manager->loadSectionsForTeam($user->field_team->entity);
// foreach ($sections as $section) {
// $grants['ghi_content_article_access'][] = $section->id();
// }
// return $grants;
// }
// @codingStandardsIgnoreEnd