-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtide_core.module
788 lines (732 loc) · 28.2 KB
/
tide_core.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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
<?php
/**
* @file
* Contains tide_core.module.
*/
use Drupal\Component\Utility\Html;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Breadcrumb\Breadcrumb;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Link;
use Drupal\Core\Render\Markup;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;
use Drupal\node\Entity\Node;
use Drupal\node\NodeInterface;
use Drupal\redirect\Entity\Redirect;
use Drupal\scheduled_transitions\Routing\ScheduledTransitionsRouteProvider;
use Drupal\tide_core\Render\Element\AdminToolbar;
use Drupal\user\RoleInterface;
use Drupal\views\ViewExecutable;
use Drupal\workflows\Entity\Workflow;
/**
* Implements hook_views_data().
*/
function tide_core_views_data() {
$data = [];
$data['views']['text_raw'] = [
'title' => t('Raw text'),
'help' => t('Add raw custom text or markup. This is similar to the custom text field.'),
'area' => [
'id' => 'text_raw',
],
];
$data['views']['sorted_roles_views_field'] = [
'title' => t('Sorted Roles'),
'help' => t('The list of user roles sorted alphabetically.'),
'field' => [
'id' => 'sorted_roles_views_field',
],
];
return $data;
}
/**
* Implements hook_views_data_alter().
*
* @see \Drupal\node\NodeViewsData::getViewsData()
* @see \Drupal\tide_core\Plugin\views\filter\StatusModerated
*/
function tide_core_views_data_alter(array &$data) {
// Add Moderation support to Node 'status_extra' filter.
// Content Overview view uses the filter 'Published status or admin user'
// without any consideration of Content Moderation. We override this filter
// to add an extra check for the 'view any unpublished content' permission
// provided by the Content Moderation module.
$data['node_field_data']['status_extra']['filter']['id'] = 'node_status_moderated';
$data['file_managed']['file_type_filter'] = [
'title' => t('Enhanced file MIME type filter'),
'filter' => [
'title' => t('Enhanced file MIME type filter'),
'help' => t('provide a custom file MIME type selection filter'),
'field' => 'filemime',
'id' => 'tide_enhanced_mime_type_filter',
],
];
}
/**
* Implements hook_views_query_substitutions().
*
* @see node_views_query_substitutions()
* @see \Drupal\node\Plugin\views\filter\Status::query()
* @see \Drupal\tide_core\Plugin\views\filter\StatusModerated::query()
*/
function tide_core_views_query_substitutions(ViewExecutable $view) {
$account = \Drupal::currentUser();
return [
'***VIEW_ANY_UNPUBLISHED_NODES***' => intval($account->hasPermission('view any unpublished content')),
];
}
/**
* Implements hook_entity_operation().
*/
function tide_core_entity_operation(EntityInterface $entity) {
// Add "Archived" operation link to entities.
$operations = [];
$workflow = Workflow::load('editorial');
if ($workflow) {
if ($workflow->getTypePlugin()
->appliesToEntityTypeAndBundle($entity->getEntityTypeId(), $entity->bundle())) {
if ($entity->access('use ' . $workflow->id() . ' transition archived')) {
$operations['archive'] = [
'title' => t('Archive'),
'weight' => 100,
'url' => Url::fromRoute('tide_core.entity.archive_confirm', [
'bundle' => $entity->getEntityTypeId(),
'entity_type_id' => $entity->id(),
]),
];
}
}
}
if ($entity->getEntityType()->hasLinkTemplate(ScheduledTransitionsRouteProvider::LINK_TEMPLATE_ADD)) {
$routeName = ScheduledTransitionsRouteProvider::getScheduledTransitionRouteName($entity->getEntityType());
$url = Url::fromRoute($routeName, [$entity->getEntityTypeId() => $entity->id()]);
$user = \Drupal::currentUser();
if (TRUE === $url->access($user)) {
$operations['scheduled_transitions'] = [
'title' => t('Scheduled updates'),
'url' => $url,
'weight' => 50,
];
}
}
return $operations;
}
/**
* Implements hook_form_alter().
*/
function tide_core_form_alter(&$form, FormStateInterface $form_state, $form_id) {
$info = \Drupal::service('entity_type.bundle.info');
foreach ($info->getBundleInfo('node') as $bundle => $item) {
if ($form_id == 'node_' . $bundle . '_scheduled_transitions_add_form_form') {
// In this form, we only keep 'publish' and 'archive' options regardless
// of what permissions the user has.
if (isset($form['scheduled_transitions']['new_meta']['transition']['#options'])) {
foreach ($form['scheduled_transitions']['new_meta']['transition']['#options'] as $key => $option) {
if (!in_array($key, ['publish', 'archive'])) {
unset($form['scheduled_transitions']['new_meta']['transition']['#options'][$key]);
}
}
}
foreach (array_keys($form['actions']) as $action) {
if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
$form['actions'][$action]['#value'] = t('Scheduled updates');
$form['actions'][$action]['#submit'][] = '_tide_core_modified_update_adding_message';
}
}
}
if ($form_id == 'node_' . $bundle . '_quick_node_clone_form') {
if (isset($form['moderation_state'])) {
$form['moderation_state']['#group'] = 'footer';
}
}
}
if ($form_id === 'menu_edit_form') {
if (isset($form_state->getUserInput()['op'])) {
if ($form_state->getUserInput()['op'] === 'Save') {
$form['actions']['submit']['#submit'][] = '_tide_core_menu_submit_handler';
}
}
}
// Re-order the user_form field.
if ($form_id === 'user_form') {
$form['account']['name']['#weight'] = 2;
$form['account']['field_business_name'] = $form['field_business_name'];
$form['account']['field_business_name']['#weight'] = 3;
unset($form['field_business_name']);
$form['account']['field_business_contact_number'] = $form['field_business_contact_number'];
$form['account']['field_business_contact_number']['#weight'] = 4;
unset($form['field_business_contact_number']);
$form['account']['field_notes'] = $form['field_notes'];
$form['account']['field_notes']['#weight'] = 5;
unset($form['field_notes']);
$form['account']['pass']['#weight'] = 6;
$form['account']['status']['#weight'] = 7;
$form['account']['roles']['#weight'] = 8;
if (isset($form['account']['notify'])) {
$form['account']['notify']['#weight'] = 9;
}
if (isset($form['account']['password_policy_status'])) {
$form['account']['password_policy_status']['#weight'] = 10;
}
}
// Update description for og_locale metatag.
if (
isset($form['field_metatags'])
&& isset($form['field_metatags']['widget'][0])
&& isset($form['field_metatags']['widget'][0]['open_graph'])
&& isset($form['field_metatags']['widget'][0]['open_graph']['og_locale'])
) {
$url = Url::fromUri('https://digital-vic.atlassian.net/servicedesk/customer/portal/27/article/2272657746', [
'attributes' => [
'target' => '_blank',
],
]);
$language_code_list_link = Link::fromTextAndUrl(t('full list of language codes'), $url)->toString();
$form['field_metatags']['widget'][0]['open_graph']['og_locale']['#description'] = t("This field is used in SDP to set the page's language, display font and text direction. See our @language-code-list.", [
'@language-code-list' => $language_code_list_link,
]);
}
}
/**
* Redirect form upon saving to the Menu UI Module collection.
*/
function _tide_core_menu_submit_handler(&$form, FormStateInterface $form_state) {
$url = Url::fromRoute('entity.menu.collection');
$form_state->setRedirectUrl($url);
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function tide_core_form_scheduled_transition_delete_form_alter(&$form, FormStateInterface $form_state, $form_id) {
$form['#title'] = t('Are you sure you want to delete the Scheduled updates?');
foreach (array_keys($form['actions']) as $action) {
if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
$form['actions'][$action]['#submit'][] = '_tide_core_modified_update_delete_message';
}
}
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function tide_core_form_user_register_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if (isset($form['account']['mail']['#required'])) {
$form['account']['mail']['#required'] = TRUE;
}
$form['account']['name']['#weight'] = 2;
$form['account']['field_business_name'] = $form['field_business_name'];
$form['account']['field_business_name']['#weight'] = 3;
unset($form['field_business_name']);
$form['account']['field_business_contact_number'] = $form['field_business_contact_number'];
$form['account']['field_business_contact_number']['#weight'] = 4;
unset($form['field_business_contact_number']);
$form['account']['field_notes'] = $form['field_notes'];
$form['account']['field_notes']['#weight'] = 5;
unset($form['field_notes']);
$form['account']['pass']['#weight'] = 6;
$form['account']['status']['#weight'] = 7;
$form['account']['roles']['#weight'] = 8;
if (isset($form['account']['notify'])) {
$form['account']['notify']['#weight'] = 9;
}
if (isset($form['account']['password_policy_status'])) {
$form['account']['password_policy_status']['#weight'] = 10;
}
}
/**
* Submit handler for altering updating status message.
*/
function _tide_core_modified_update_adding_message(&$form, $form_state) {
$messenger = \Drupal::messenger();
$messenger->deleteByType('status');
$onDate = $form_state->getValue(['on']);
$messenger->addMessage(t('Scheduled an update for @date', [
'@date' => \Drupal::service('date.formatter')
->format($onDate->getTimestamp()),
]));
}
/**
* Submit handler for altering deleting status message.
*/
function _tide_core_modified_update_delete_message(&$form, $form_state) {
$messenger = \Drupal::messenger();
$messenger->deleteByType('status');
$messenger->addMessage(t('The Scheduled update has been deleted.'), 'status');
}
/**
* Implements hook_menu_links_discovered_alter().
*/
function tide_core_menu_links_discovered_alter(&$links) {
if (isset($links['entity.scheduled_transition.collection']['title'])) {
$links['entity.scheduled_transition.collection']['title'] = 'Scheduled updates';
}
// @todo delete after scheduled_updates module fully uninstalled.
if (isset($links['entity.scheduled_update.collection'])) {
unset($links['entity.scheduled_update.collection']);
}
}
/**
* Implements hook_menu_local_actions_alter().
*/
function tide_core_menu_local_actions_alter(&$local_actions) {
if (isset($local_actions['scheduled_transitions.actions:node.add_scheduled_transition']['title'])) {
$local_actions['scheduled_transitions.actions:node.add_scheduled_transition']['title'] = 'Add Scheduled update';
}
}
/**
* Implements hook_local_tasks_alter().
*/
function tide_core_local_tasks_alter(&$local_tasks) {
if (isset($local_tasks['scheduled_transitions.tasks:node.scheduled_transitions']['title'])) {
$local_tasks['scheduled_transitions.tasks:node.scheduled_transitions']['title'] = 'Scheduled updates';
}
// @todo delete after scheduled_updates module fully uninstalled.
if (isset($local_tasks['scheduled_update.admin'])) {
unset($local_tasks['scheduled_update.admin']);
}
}
/**
* Implements hook_preprocess_HOOK().
*/
function tide_core_preprocess_status_messages(&$variables) {
if (isset($variables['message_list']['error']) && !empty($variables['message_list']['error'])) {
foreach ($variables['message_list']['error'] as &$error_message) {
if ($error_message instanceof Markup) {
$message = $error_message->__toString();
// We want to ensure that the error message to be altered under
// node edit context.
preg_match('/entity:node\/(\d+)/', $message, $matches);
// Checking that the error message comes from field_paragraph_link based
// on a node context.
if (strpos($message, 'Validation error on collapsed paragraph field_paragraph_link') !== FALSE && (isset($matches[1]) && is_numeric($matches[1]))) {
$error_message = t('A link in <i>Related links</i> field on this page is broken. Please update or remove the link and retry.');
}
}
}
}
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function tide_core_form_content_moderation_entity_moderation_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if (isset($form['revision_log'])) {
$form['#attached']['library'][] = 'tide_core/content_moderation';
$form['#attached']['library'][] = 'tide_core/node_revision_log';
$form['revision_log']['#type'] = 'textarea';
$form['revision_log'] = _tide_core_revision_log_form_label_text() + $form['revision_log'];
$form['#validate'][] = '_tide_core_node_form_log_message_validate';
}
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function tide_core_form_editor_link_dialog_alter(&$form, FormStateInterface $form_state, $form_id) {
// Alter only the form with ID 'editor_link_dialog'.
if ($form_id !== 'editor_link_dialog') {
return;
}
$form['#attached']['library'][] = 'tide_core/editor_autolink';
// Updating the default title and description.
if (isset($form['attributes']['href'])) {
$form['attributes']['href']['#title'] = t('URL, phone number or email address');
$form['attributes']['href']['#description'] = t('External links must include https://. Type or paste a phone number or email address and click Enter to add the hyperlink. For more information read our <strong><a href="https://www.singledigitalpresence.vic.gov.au/hyperlinks" target="_blank">guide on hyperlinks</a></strong>.');
}
}
/**
* Common revision log message form label text.
*
* @return array
* Form API key values.
*/
function _tide_core_revision_log_form_label_text(): array {
return [
'#title' => t('Change request detail'),
'#description' => t('Use this field to specify details of changes made in this update. If content is embargoed or time specific, enter the scheduling details. <br /> <br />
Keep the content in <strong>Draft</strong> until you are ready to publish. Content publishing or archiving requests will be actioned within <strong>2 business days</strong>. <br /> <br />
Contact your department content team for urgent publishing requests.'),
];
}
/**
* A validate handler on the moderation form.
*
* Check log message is required when status is needs_review or archive_pending.
*
* @param array $form
* The form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*/
function _tide_core_node_form_log_message_validate(array &$form, FormStateInterface $form_state) {
$new_state = $form_state->getValue('new_state');
$require_logs = ['needs_review', 'archive_pending'];
$revision_log = $form_state->getValue('revision_log');
if (in_array($new_state, $require_logs) && empty($revision_log)) {
$form_state->setErrorByName('revision_log', t('The publisher comments field must not be blank'));
}
}
/**
* Implements hook_preprocess_HOOK().
*/
function tide_core_preprocess_page(&$variables) {
$variables['#attached']['library'][] = 'tide_core/ckeditor_stylesheets';
}
/**
* Implements hook_editor_js_settings_alter().
*/
function tide_core_editor_js_settings_alter(array &$settings) {
foreach (array_keys($settings['editor']['formats']) as $text_format_id) {
$settings['editor']['formats'][$text_format_id]['editorSettings']['contentsCss'][] = '/' . \Drupal::service('extension.list.module')->getPath('tide_core') . '/css/ckeditor_overrides.css';
}
}
/**
* Implements hook_form_FORM_ID_alter().
*
* Move some core fields to Node form Sidebar.
*/
function tide_core_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
$form['#attached']['library'][] = 'tide_core/claro_layout';
$form['#attached']['library'][] = 'tide_core/node_iframe';
$form['#attached']['library'][] = 'tide_core/sticky_node_form_sidebar';
$form['#process'][] = '_tide_core_form_node_form_process';
$form['#attached']['library'][] = 'tide_core/pseudo_required_field';
// Adding custom states from webform js.
// Support patterns in states.
if (\Drupal::moduleHandler()->moduleExists('webform')) {
$form['#attached']['library'][] = 'webform/webform.states';
}
$node = $form_state->getFormObject()->getEntity();
// Modify field_content_category help text.
if ($node->hasField('field_content_category')) {
$newLabelDescription = [
'#type' => 'inline_template',
'#template' => '<span style="font-weight: bold;">{{ title }}</span>
<span class="pseudo-required-field">{{ asterisk }}</span>
<div style="font-size: 0.85em; color: #595959;">{{ description }}</div>',
'#context' => [
'title' => (isset($form['field_content_category']['widget']['#required'])) ? $form['field_content_category']['widget']['#title'] : '',
'description' => (isset($form['field_content_category']['widget']['#description'])) ? $form['field_content_category']['widget']['#description'] : '',
'asterisk' => (isset($form['field_content_category']['widget']['#required']) && $form['field_content_category']['widget']['#required'] == TRUE) ? '*' : '',
],
];
$form['field_content_category']['#prefix'] = \Drupal::service('renderer')->renderPlain($newLabelDescription);
if (isset($form['field_content_category']['widget']['#description'])) {
$form['field_content_category']['widget']['#description'] = '';
}
$form['field_content_category']['widget']['#title_display'] = 'invisible';
}
// Apply to edit form only, tide_workflow_notification_form_node_form_alter.
if ($node->isNew()) {
return;
}
// Add comment log message field.
if (isset($form['revision_log']) && $form['revision_log']['#access']) {
$form['moderation_state']['comment_log_message'] = _tide_core_revision_log_form_label_text() + [
'#type' => 'textarea',
'#rows' => 3,
'#weight' => 9,
];
$form['#validate'][] = '_tide_core_node_edit_form_log_message_validate';
$form['#attached']['library'][] = 'tide_core/node_revision_log';
}
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function tide_core_form_revision_overview_form_alter(&$form, FormStateInterface $form_state, $form_id) {
// Adding headers to unlabelled radio button options.
if (isset($form['node_revisions_table'])) {
$form['node_revisions_table']['#header']['select_column_one'] = "Compare From";
$form['node_revisions_table']['#header']['select_column_two'] = "Compare To";
}
}
/**
* A validate handler on the node form.
*
* Check log message ir required when status is needs_review or archive_pending.
*
* @param array $form
* The form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*/
function _tide_core_node_edit_form_log_message_validate(array &$form, FormStateInterface $form_state) {
if (!$form['revision_log']['#access'] || $form_state->getValue('moderation_state') === NULL) {
return;
}
$moderation_state = reset($form_state->getValue('moderation_state'));
$require_logs = ['needs_review', 'archive_pending'];
$revision_log = reset($form_state->getValue('revision_log'));
if (in_array($moderation_state['value'], $require_logs) && empty($revision_log['value'])) {
$form_state->setErrorByName('comment_log_message', t('The publisher comments field must not be blank'));
}
}
/**
* Node form #process callback.
*
* @param array $element
* Form that is being processed.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
* @param array $form
* The complete form structure.
*
* @return array
* The processed form.
*/
function _tide_core_form_node_form_process(array $element, FormStateInterface $form_state, array $form = []) {
/** @var \Drupal\node\NodeInterface $node */
$node = $form_state->getFormObject()->getEntity();
$element['tide_core_metadata'] = [
'#type' => 'container',
'#open' => TRUE,
'#optional' => TRUE,
'#access' => TRUE,
'#group' => 'meta',
'#attributes' => [
'class' => ['tide-core-metadata'],
],
'#weight' => 100,
];
$core_fields = [
10 => 'field_node_department',
20 => 'field_tags',
];
foreach ($core_fields as $weight => $core_field) {
if ($node->hasField($core_field)) {
if (isset($element[$core_field])) {
$element[$core_field]['#group'] = 'tide_core_metadata';
$element[$core_field]['#weight'] = $weight;
}
}
}
return $element;
}
/**
* Implements hook_ENTITY_TYPE_access().
*/
function tide_core_menu_link_content_access(EntityInterface $menu_link_item, $operation, AccountInterface $account) {
if ($menu_link_item->hasField('link') && !$menu_link_item->link->isEmpty()) {
$url = $menu_link_item->getUrlObject();
if (!$url->isExternal() && $url->isRouted() && $menu_link_item->isPublished()) {
$parameters = $url->getRouteParameters();
if (isset($parameters['node'])) {
$node = Node::load($parameters['node']);
if ($node instanceof NodeInterface) {
$menu_link_item->addCacheableDependency($node);
if ($account->hasPermission('administer menu')) {
return AccessResult::neutral()->addCacheableDependency($menu_link_item);
}
if (!$node->isPublished()) {
return AccessResult::forbidden()->addCacheableDependency($menu_link_item);
}
if ($node->hasField('moderation_state') && !$node->moderation_state->isEmpty()) {
if ($node->moderation_state->value !== 'published') {
return AccessResult::forbidden()->addCacheableDependency($menu_link_item);
}
}
}
return AccessResult::neutral()->addCacheableDependency($menu_link_item);
}
}
}
}
/**
* Implements hook_ENTITY_TYPE_presave() for redirect entities.
*/
function tide_core_redirect_presave(Redirect $redirect) {
$cids = [];
$matches = [];
$redirect_node = [];
if (is_numeric($redirect->id())) {
array_push($cids, 'redirect:' . $redirect->id());
}
// Because of the field type the extraction of node id is in this way.
$source_alias = \Drupal::service('path_alias.manager')->getPathByAlias($redirect->getSourceUrl());
if ($source_alias && preg_match('/node\/(\d+)/', $source_alias, $matches)) {
if (isset($matches) && array_key_exists(1, $matches) && is_numeric($matches[1])) {
array_push($cids, 'node:' . $matches[1]);
}
}
// If internal route.
if ($redirect->getRedirectUrl()->isRouted()) {
// Get the Redirect node Id.
if (!is_bool($redirect->getRedirectUrl())) {
$redirect_node = $redirect->getRedirectUrl()->getRouteParameters();
if ($redirect_node && array_key_exists('node', $redirect_node)) {
if (is_numeric($redirect_node['node'])) {
array_push($cids, 'node:' . $redirect_node['node']);
}
}
}
}
// Invalidate the Cache tags.
if (!empty($cids)) {
Cache::invalidateTags($cids);
}
}
/**
* Implements hook_node_access_records().
*/
function tide_core_node_access_records(NodeInterface $node) {
if (!$node->isPublished()) {
$grants = [];
$grants[] = [
'realm' => 'tide_core',
'gid' => 1,
'grant_view' => 1,
'grant_update' => 0,
'grant_delete' => 0,
'nid' => $node->id(),
];
return $grants;
}
return [];
}
/**
* Implements hook_node_grants().
*/
function tide_core_node_grants(AccountInterface $account, $op) {
if ($op === 'view') {
$view_unpublished_content_roles = array_keys(user_roles(TRUE, 'view any unpublished content'));
$account_roles = $account->getRoles();
if (!empty(array_intersect($account_roles, $view_unpublished_content_roles))) {
$grants = [];
$grants['tide_core'][] = 1;
return $grants;
}
}
return [];
}
/**
* Implements hook_node_access().
*/
function tide_core_node_access(NodeInterface $node, $op, AccountInterface $account) {
// Only run if the module permission by terms is enabled.
if (!$node->isPublished() && $op === 'view') {
$access_result = AccessResult::allowedIfHasPermission($account, 'view any unpublished content');
$access_result = $access_result->andIf(AccessResult::allowedIf($node->getOwnerId() == $account->id() || $node->getRevisionUserId() == $account->id()));
return $access_result->addCacheableDependency($node);
}
return AccessResult::neutral()->addCacheableDependency($node);
}
/**
* Implements hook_system_breadcrumb_alter().
*
* @todo Follow up with the issue.
* @see https://www.drupal.org/project/drupal/issues/3220437
*/
function tide_core_system_breadcrumb_alter(Breadcrumb &$breadcrumb, RouteMatchInterface $route_match, array $context) {
if (!empty($breadcrumb)) {
$links = $breadcrumb->getLinks();
$route = $route_match->getRouteName();
if (isset($links[1]) && !empty($route)) {
$link = $links[1]->getUrl()->toString();
$routes = [
'entity.node.delete_form',
'entity.node.version_history',
'entity.node.entity_hierarchy_reorder',
'entity.node.scheduled_transitions',
'entity.share_link_token.node_collection',
];
if (in_array($route, $routes) && $link = '/node') {
$links[1]->setText('Node');
}
}
}
}
/**
* Implements hook_ENTITY_TYPE_presave().
*/
function tide_core_node_presave(NodeInterface $node) {
$node_state = isset($node->get('moderation_state')->getValue()[0]) ? $node->get('moderation_state')->getValue()[0]['value'] : '';
if ($node_state === 'published') {
$log = [
/*
* Term the 'type' => 'node' as 'type' => 'page'
* to improve log readability.
*/
'type' => 'page',
'operation' => 'published',
'description' => t('%type: %title - New page created with workflow state %new_state', [
'%type' => $node->getType(),
'%title' => $node->getTitle(),
'%new_state' => $node_state,
]),
'ref_numeric' => $node->id(),
'ref_char' => $node->getTitle(),
];
// Add the log to the "admin_audit_trail" table.
if (function_exists('admin_audit_trail_insert')) {
admin_audit_trail_insert($log);
}
}
}
/**
* Implements hook_admin_audit_trail_handlers().
*/
function tide_core_admin_audit_trail_handlers() {
// Page event log handler.
$handlers = [];
$handlers['page'] = [
'title' => t('Page'),
];
return $handlers;
}
/**
* Adds toolbar-specific attributes to the menu link tree.
*
* @param \Drupal\Core\Menu\MenuLinkTreeElement[] $tree
* The menu link tree to manipulate.
*
* @return \Drupal\Core\Menu\MenuLinkTreeElement[]
* The manipulated menu link tree.
*/
function tide_core_menu_navigation_links(array $tree) {
foreach ($tree as $element) {
// Remove menu and taxonomy subtree.
if (($element->link->getPluginId() === 'entity.menu.collection' || $element->link->getPluginId() === 'entity.taxonomy_vocabulary.collection') && isset($element->subtree)) {
$element->subtree = [];
}
if (($element->link->getPluginId() != 'entity.menu.collection')
&& ($element->link->getPluginId() != 'entity.taxonomy_vocabulary.collection')
&& $element->subtree) {
tide_core_menu_navigation_links($element->subtree);
}
$link = $element->link;
// Get the non-localized title to make the icon class.
$definition = $link->getPluginDefinition();
$element->options['attributes']['class'][] = 'toolbar-icon';
$string = strtolower(str_replace(['.', ' ', '_'], ['-', '-', '-'], $definition['id']));
$element->options['attributes']['class'][] = Html::cleanCssIdentifier('toolbar-icon-' . $string);
$element->options['attributes']['title'] = $link->getDescription();
}
return $tree;
}
/**
* Implements hook_toolbar_alter().
*/
function tide_core_toolbar_alter(&$items) {
$items['administration']['tray']['toolbar_administration']['#pre_render'] = [
[
AdminToolbar::class,
'preRenderTray',
],
];
}
/**
* Implements hook_ENTITY_TYPE_insert().
*
* This is necessary because of a circular dependency between the 'site_admin'
* role and the 'assign site_admin role' permission.
*
* @see https://www.drupal.org/project/role_delegation/issues/3354012
*/
function tide_core_user_role_insert(RoleInterface $role): void {
if ($role->id() === 'site_admin') {
$role->grantPermission('assign site_admin role');
$role->save();
}
}