This repository has been archived by the owner on Sep 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmessage_integration.module
405 lines (358 loc) · 12.7 KB
/
message_integration.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
<?php
/**
* @file
* Holds hook implementation for the Custom Message Integration module.
*/
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\Node;
use Drupal\comment\Entity\Comment;
use Drupal\user\Entity\User;
use Drupal\message\Entity\Message;
use Drupal\message_subscribe\Subscribers\DeliveryCandidate;
use Drupal\Core\Asset\AttachedAssets;
use TijsVerkoyen\CssToInlineStyles\CssToInlineStyles;
use Drupal\Component\Utility\Html;
use Drupal\Core\Render\Markup;
use Drupal\Component\Render\MarkupInterface;
/**
* The content types whose changes should generate messages.
*/
define('MESSAGE_INTEGRATION_CONTENT_TYPES', ['blog', 'book_page', 'policy_page']);
/**
* Implementation of hook_cron().
*
* Fix repeating media error messages in email.
*
* The following error is repeated for every image sent in queued emails,
* once 20 images have been rendered.
* - "During rendering of embedded media: recursive rendering detected..."
*
* The problem is core refuses to render the same image more than 20 times in
* one session, even if it's to create content for different users. This
* happens when emails are sent all at once during cron.
*
* The workaround is to use queue_throttle to limit the number of emails sent
* in a single session. After experimentation, more than 9 items sent at once
* may start to trigger errors.
*
* @see https://www.drupal.org/project/drupal/issues/2940605
*/
function message_integration_cron() {
$options = [
'items' => 9,
'unit' => 'minute',
'time-limit' => 30,
];
\Drupal::service('queue_throttle.cron')->run('message_subscribe', $options);
}
/**
* Implements hook_swiftmailer_alter().
*
* Core fixes relative links in MailManager, but Swiftmailer sets the body too
* late. This is a workaround for a Swiftmailer issue. Without this, links in
* the emailed message are relative links, which don't work in email.
*
* @see https://www.drupal.org/project/swiftmailer/issues/3126636
*/
function message_integration_swiftmailer_alter(Swift_Mailer &$swiftMailer, Swift_Message &$swiftMessage, $message) {
if (!empty($message['params']['message_entity'])) {
$text = $swiftMessage->getBody();
if ($text instanceof MarkupInterface) {
$text = Markup::create(Html::transformRootRelativeUrlsToAbsolute((string) $text, \Drupal::request()->getSchemeAndHttpHost()));
$swiftMessage->setBody($text);
}
}
}
/**
* Implemenation of hook_form_BASE_FORM_ID_alter().
*/
function message_integration_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
// Provide a notification message for authors so they know what will happen.
$form_object = $form_state->getFormObject();
if ($form_object instanceof EntityForm) {
$entity = $form_object->getEntity();
if (in_array($entity->bundle(), MESSAGE_INTEGRATION_CONTENT_TYPES)) {
// Add reminders about which actions will send messages.
$form['title']['#suffix'] = '<div class="notification-message">' .
t("Message notification is enabled.") . " " .
t("Users will automatically be notified when content is published and when comments are added.") .
'</div>';
}
}
}
/**
* Get css for the mailed messages.
*
* CSS is the same for all messages, so cache it.
*
* @return string
* A string containing an aggregate of all css on all mail-related libraries.
*/
function message_integration_css() {
$cid = 'message_integration_css';
$css = NULL;
if ($cache = \Drupal::cache()->get($cid)) {
$css = $cache->data;
}
else {
// Mail and Swiftmail ignore libraries when rendering messages. Our messages
// represent nodes and comments, and we need libraries for the HTML messages
// to look right. So we identify css libraries needed for email and attach
// them here.
$assets = AttachedAssets::createFromRenderArray([
'#attached' => [
'library' => [
'core/normalize',
'olivero/global-styling',
'olivero_dr/global-styling',
'olivero_mail/global-styling',
'diff/diff.single_column',
'diff/diff.colors',
'diff/diff.general',
],
],
]);
$assetResolver = \Drupal::service('asset.resolver');
$fileSystem = \Drupal::service('file_system');
foreach ($assetResolver->getCssAssets($assets, FALSE) as $css_asset) {
$css .= file_get_contents($fileSystem->realpath($css_asset['data']));
}
\Drupal::cache()->set($cid, $css);
}
return $css;
}
/**
* Implements hook_message_view_alter().
*/
function message_integration_message_view_alter(array &$build) {
$build['#post_render'][] = 'message_integration_post_render';
}
/**
* Post render callback.
*
* @param string $text
* The rendered text.
* @param array $context
* Context for the rendered content.
*
* @return string
* The altered text.
*/
function message_integration_post_render($text, array $context) {
// For email we don't want linked css files in the HEAD of the page, we
// want css to be inlined into the body. So we construct a single string of
// css, then use CssToInlineStyles() to render that css inline in the markup.
if ($css = message_integration_css()) {
$text = (new CssToInlineStyles())->convert($text, $css);
}
return $text;
}
/**
* Implements hook_preprocess_field().
*/
function message_integration_preprocess_field(&$variables) {
// When rendering comments in the `message` view mode used for email, hide
// the new comment form.
$element = $variables['element'];
if ($element['#field_type'] == 'comment') {
if ($variables['element']['#view_mode'] == 'message') {
unset($variables['comment_form']);
}
}
}
/**
* Implements hook_node_insert().
*/
function message_integration_node_insert(Node $node) {
// See if this handling should be skipped.
$config = \Drupal::config('message_integration.settings');
$skip = $config->get('skip');
if (!empty($skip)) {
return;
}
if (!in_array($node->bundle(), MESSAGE_INTEGRATION_CONTENT_TYPES)) {
return;
}
// If newly created node is published, queue messages to notify all the node
// subscribers about published node.
if ($node->isPublished()) {
// Create a message.
$template = $node->isPublished() ? 'publish_node' : 'create_node';
$message = Message::create(['template' => $template, 'uid' => $node->getOwnerId()]);
$message->set('field_node_reference', $node);
$message->set('field_published', $node->isPublished());
$message->save();
$subscribers = \Drupal::service('message_subscribe.subscribers');
// Create a custom subscriber list to notify all active users.
// This is an end run around the normal flag subscription system since we
// don't want to subscribe every user to every piece of content.
$subscribe_options = message_integration_subscribe_options();
$options = $subscribe_options;
foreach ($subscribe_options['uids'] as $uid => $values) {
$options['uids'] = [$uid => $values];
$subscribers->sendMessage($node, $message, [], $options);
}
}
}
/**
* Implements hook_node_update().
*/
function message_integration_node_update(Node $node) {
// See if this handling should be skipped.
$config = \Drupal::config('message_integration.settings');
$skip = $config->get('skip');
if (!empty($skip)) {
return;
}
// If this isn't a content type that we create messages for, do nothing.
if (!in_array($node->bundle(), MESSAGE_INTEGRATION_CONTENT_TYPES)) {
return;
}
// If we're not updating the default revision, do nothing.
if (!$node->isDefaultRevision()) {
return;
}
// Match publication status of message to status of source entity.
message_integration_update_message_status($node);
// If the node is not published, do nothing more.
if (!$node->isPublished()) {
return;
}
// See if this is a newly-published node.
$original = !empty($node->original) ? $node->original : $node;
if ($node->isPublished() && !$original->isPublished()) {
$template = 'publish_node';
$newly_published = TRUE;
}
else {
$template = 'update_node';
$newly_published = FALSE;
}
// See if this is a new revision and whether anything changed.
$langcode = $node->language()->getId();
$new_vid = $node->vid->value;
if ($node->hasTranslation($langcode) && !$node->getTranslation($langcode)->isRevisionTranslationAffected()) {
// If nothing changed, the system won't treat this as a new revision.
$original_vid = $new_vid;
$new_revision = FALSE;
}
else {
$original_vid = $original->vid->value;
$new_revision = $original_vid != $new_vid ? TRUE : FALSE;
}
// If this is a new revision where nothing changed and it wasn't published,
// skip message altogether.
if (!$new_revision && !$newly_published) {
return;
}
// Create a message.
$message = Message::create([
'template' => $template,
'uid' => $node->getOwnerId(),
]);
$message->set('field_node_reference', $node);
$message->set('field_published', $node->isPublished());
// Store original and current vids, so the right diff can be shown in the
// node-diff token.
if ($message->hasField('field_new_vid')) {
$message->set('field_new_vid', $new_vid);
}
if ($message->hasField('field_original_vid')) {
$message->set('field_original_vid', $original_vid);
}
$message->save();
$subscribers = \Drupal::service('message_subscribe.subscribers');
// Create a custom subscriber list to notify all active users.
// This is an end run around the normal flag subscription system since we
// don't want to subscribe every user to every piece of content.
$subscribe_options = message_integration_subscribe_options();
$options = $subscribe_options;
foreach ($subscribe_options['uids'] as $uid => $values) {
$options['uids'] = [$uid => $values];
$subscribers->sendMessage($node, $message, [], $options);
}
}
/**
* Implements hook_comment_insert().
*/
function message_integration_comment_insert(Comment $comment) {
// See if this handling should be skipped.
$config = \Drupal::config('message_integration.settings');
$skip = $config->get('skip');
if (!empty($skip)) {
return;
}
$node = $comment->get('entity_id')->first()->get('entity')->getTarget()->getValue();
if (!in_array($node->bundle(), MESSAGE_INTEGRATION_CONTENT_TYPES)) {
return;
}
// Create a message.
$message = Message::create([
'template' => 'create_comment',
'uid' => $node->getOwnerId(),
]);
$message->set('field_comment_reference', $comment);
$message->set('field_published', $comment->isPublished());
$message->save();
// Queue messages to notify all the node subscribers about new comment.
$subscribers = \Drupal::service('message_subscribe.subscribers');
// Create a custom subscriber list to notify all active users.
// This is an end run around the normal flag subscription system since we
// don't want to subscribe every user to every piece of content.
$subscribe_options = message_integration_subscribe_options();
$options = $subscribe_options;
foreach ($subscribe_options['uids'] as $uid => $values) {
$options['uids'] = [$uid => $values];
$subscribers->sendMessage($node, $message, [], $options);
}
}
/**
* Set message entity published field when it changes in the related entity.
*
* @param \Drupal\Core\Entity\ContentEntityBase $entity
* The entity object.
*/
function message_integration_update_message_status(ContentEntityBase $entity) {
if (!empty($entity->original) && $entity->isPublished() == $entity->original->isPublished()) {
return;
}
$query = \Drupal::entityQuery('message');
$field = 'field_' . $entity->getEntityType()->id() . '_reference';
$query->condition($field . '.target_id', $entity->id());
$results = $query->execute();
if (empty($results)) {
return;
}
$messages = Message::loadMultiple($results);
foreach ($messages as $message) {
$message->set('field_published', $entity->isPublished());
$message->save();
}
}
/**
* Helper to create custom subscriber list.
*
* Hard-coding 'uids' in $subscribe_options will cause message_subscribe to
* skip other subscribers and send to just this list, so this allows us
* to create a custom subscription list.
*
* @return array
* Array of subscribe_options to use when sending the message.
*/
function message_integration_subscribe_options() {
$query = \Drupal::entityQuery('user')
->condition('status', 1);
$query->condition('uid', [0, 1], 'NOT IN');
$subscribe_uids = $query->execute();
$notifiers = ['email'];
$subscribe_options = [
'notify message owner' => FALSE,
'uids' => [],
];
foreach ($subscribe_uids as $uid) {
$subscribe_options['uids'][$uid] = new DeliveryCandidate([], $notifiers, $uid);
}
return $subscribe_options;
}